如何从一个脚本调用另一个脚本?

478 投票
17 回答
865458 浏览
提问于 2025-04-15 13:11

我有一个叫做 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 个回答

128

另一种方法:

文件 test1.py:

print "test1.py"

文件 service.py:

import subprocess

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

这种方法的好处是,你不需要修改现有的 Python 脚本,把所有代码都放到一个子程序里。

文档链接: Python 2, Python 3

235

在Python 2中,可以使用execfile来实现这个功能:

execfile("test2.py")

在Python 3中,可以使用exec来实现这个功能:

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

如果这对你来说很重要,可以查看文档了解命名空间的处理。

不过,你应该考虑使用其他方法;从我看到的情况来看,你的想法看起来不是很清晰。

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

撰写回答