如何最好地从另一个脚本调用脚本?

2024-04-25 23:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

文件test1.py

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

文件服务.py

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

我知道有一种方法是打开文件,读取内容,并基本上对其进行评估。我想有更好的办法。或者至少我希望如此。


Tags: 模块文件方法函数代码pytest脚本
3条回答

这在Python 2中是可能的,使用

execfile("test2.py")

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

在Python 3中,这是可以使用的(多亏了@fantatory)

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

但是,你应该考虑使用不同的方法;你的想法(从我所看到的)看起来不太清晰。

通常的方法如下。

测试1.py

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

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

服务.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:

print "test1.py"

文件服务.py:

import subprocess

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

这种方法的优点是不必编辑现有的Python脚本就可以将其所有代码放入子例程中。

文档:Python 2Python 3

相关问题 更多 >