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

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


当前回答

通常的做法是这样的。

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版本,

假设你想在一个'if'条件中执行一个名为' recommendation .py'的脚本,然后使用,

if condition:
       import recommend

技术是不同的,但有效!

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

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 os

os.system("python myOtherScript.py arg1 arg2 arg3")  

使用操作系统,您可以直接呼叫您的终端。如果你想更具体,你可以连接你的输入字符串与局部变量,即。

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

这是一个带有子进程库的例子:

import subprocess

python_version = '3'
path_to_run = './'
py_name = '__main__.py'

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # works in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]

res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

另一种方法:

文件test1.py:

print "test1.py"

文件service.py:

import subprocess

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

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

文档:Python 2, Python 3