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

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


当前回答

一个使用子进程的例子。

从子进程导入运行

导入系统

([系统运行。可执行文件,“fullpathofyourfile.py”)

其他回答

为什么不直接导入test1?每个python脚本都是一个模块。更好的方法是在test1.py中添加一个函数main/run,导入test1并运行test1.main()。或者可以将test1.py作为子进程执行。

通常的做法是这样的。

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

如果你想让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

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

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

这可以在Python 2中使用

execfile("test2.py")

如果对您的情况很重要,请参阅文档了解名称空间的处理。

在Python 3中,可以使用(感谢@fantastory)

exec(open("test2.py").read())

然而,你应该考虑使用不同的方法;(在我看来)你的想法不太清楚。