如何从一个脚本调用另一个脚本?
我有一个叫做 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
17 个回答
378
通常我们可以这样做:
这是一个名为 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()