我有一个名为test1.py的脚本,它不在模块中。它只有在脚本本身运行时应该执行的代码。没有函数、类、方法等。我有另一个脚本作为服务运行。我想从作为服务运行的脚本调用test1.py。

例如:

文件test1.py:

print "I am a test"
print "see! I do nothing productive."

文件service.py:

# Lots of stuff here
test1.py # do whatever is in test1.py

我知道有一种方法是打开文件,读取内容,然后对它求值。我想应该有更好的方法。至少我希望如此。


当前回答

import os

os.system("python myOtherScript.py arg1 arg2 arg3")  

使用操作系统,您可以直接呼叫您的终端。如果你想更具体,你可以连接你的输入字符串与局部变量,即。

command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)

其他回答

通常的做法是这样的。

test1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

service.py

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()

我更喜欢runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

正如前面提到的,runpy是运行当前脚本中的其他脚本或模块的好方法。

顺便说一下,跟踪器或调试器通常会这样做,在这种情况下,直接导入文件或在子进程中运行文件等方法通常是行不通的。

使用exec运行代码也需要注意。您必须提供适当的run_globals以避免导入错误或其他问题。参考runpy。查看详细信息_run_code。

根据上面的例子,这是最好的方法:

# test1.py

def foo():
    print("hellow")
# test2.py
from test1 import foo # might be different if in different folder.
foo()

但根据标题,使用os.startfile(“path”)是最好的方法,因为它很小,而且它可以工作。这将执行指定的文件。我的python版本是3。x +。

如果你想让test1.py保持可执行的功能,就像在service.py内部调用它一样,然后做如下的事情:

test1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

service.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py