从另一个Python脚本调用Python脚本的最好方法是什么?

我有一个名为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 

我知道有一种方法是打开文件,阅读内容,并基本评估它。 我假设有一个更好的方法来做到这一点。 或者至less我希望如此。

通常的做法如下。

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() 

这在Python 2中可以使用

 execfile("test2.py") 

请参阅处理命名空间的文档 (如果您的情况很重要)。

但是,您应该考虑使用不同的方法; 你的想法(从我所看到的)看起来不是很干净。

其他方式:

文件test1.py:

 print "test1.py" 

文件service.py:

 import subprocess subprocess.call("test1.py", shell=True) 

这种方法的好处是,你不必编辑一个现有的Python脚本,把所有的代码放到一个子程序中。

文档: Python 2 , Python 3

如果你想让test1.py保持可执行的function,就像在service.py中调用它的function一样,然后执行如下操作:

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 

你不应该这样做。 相反,做:

test1.py:

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

service.py

 #near the top from test1 import print_test #lots of stuff here print_test() 

使用import test1进行第一次使用 – 它将执行脚本。 对于以后的调用,将脚本视为导入的模块,并调用reload(test1)方法。

reload(module)执行时:

  • Python模块的代码被重新编译, 模块级代码被重新执行 ,定义了一组绑定到模块字典中名称的新对象。 扩展模块的init函数不被调用

sys.modules的简单检查可以用来调用适当的操作。 要继续将脚本名称作为string( 'test1' )引用,请使用' import ()'内build。

 import sys if sys.modules.has_key['test1']: reload(sys.modules['test1']) else: __import__('test1') 
 import os os.system("python myOtherScript.py arg1 arg2 arg3") 

使用操作系统,您可以直接拨打您的terminal。 如果你想更具体,你可以连接你的inputstring与本地variables,即。

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

为什么不只是导入test1? 每个python脚本都是一个模块。 更好的方法是在test1.py,import test1和run test1.main()中运行main / run等函数,或者执行test1.py作为subprocess。