我有一个名为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?每个python脚本都是一个模块。更好的方法是在test1.py中添加一个函数main/run,导入test1并运行test1.main()。或者可以将test1.py作为子进程执行。

其他回答

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

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

第一次使用import test1 -它将执行脚本。对于以后的调用,将脚本视为导入的模块,并调用reload(test1)方法。

当reload(module)执行时: Python模块的代码被重新编译,模块级代码被重新执行,定义一组新的对象,这些对象被绑定到模块字典中的名称。扩展模块的init函数没有被调用

一个简单的检查sys。模块可用于调用适当的操作。要继续将脚本名称引用为字符串('test1'),请使用内置的'import()'。

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

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

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

我更喜欢runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

I found runpy standard library most convenient. Why? You have to consider case when error raised in test1.py script, and with runpy you are able to handle this in service.py code. Both traceback text (to write error in log file for future investigation) and error object (to handle error depends on its type): when with subprocess library I wasn't able to promote error object from test1.py to service.py, only traceback output. Also, comparing to "import test1.py as a module" solution, runpy is better cause you have no need to wrap code of test1.py into def main(): function.

代码片段为例,使用traceback模块捕获最后一个错误文本:

import traceback
import runpy #https://www.tutorialspoint.com/locating-and-executing-python-modules-runpy

from datetime import datetime


try:
    runpy.run_path("./E4P_PPP_2.py")
except Exception as e:
    print("Error occurred during execution at " + str(datetime.now().date()) + " {}".format(datetime.now().time()))
    print(traceback.format_exc())
    print(e)