使用子进程在 python 脚本中调用带有输入的 python 脚本

Calling a python script with input within a python script using subprocess

我有一个脚本 a.py,在执行它时会向用户询问某些查询,并以 json 格式构建输出。使用 python 子进程,我可以从另一个名为 b.py 的脚本调用此脚本。一切都按预期工作,只是我无法在变量中获取输出?我在 Python 3.

中这样做

使用 subprocess 模块从另一个脚本调用 Python 脚本并向其传递一些输入并获取其输出:

#!/usr/bin/env python3
import os
import sys
from subprocess import check_output

script_path = os.path.join(get_script_dir(), 'a.py')
output = check_output([sys.executable, script_path],
                      input='\n'.join(['query 1', 'query 2']),
                      universal_newlines=True)

其中 get_script_dir() function is defined here.

一个更灵活的替代方案是导入模块 a 并调用一个函数来获取结果(确保 a.py 使用 if __name__=="__main__" 保护,以避免 运行在导入时使用不需要的代码):

#!/usr/bin/env python
import a # the dir with a.py should be in sys.path

result = [a.search(query) for query in ['query 1', 'query 2']]

您可以在单独的进程中使用 mutliprocessing 到 运行 每个查询(如果执行查询是 CPU 密集的,那么它可能会提高时间性能):

#!/usr/bin/env python
from multiprocessing import freeze_support, Pool
import a

if __name__ == "__main__":
   freeze_support()
   pool = Pool() # use all available CPUs
   result = pool.map(a.search, ['query 1', 'query 2'])

另一种未提及的方法是使用内置函数 exec
该函数获取一串python代码并执行
要在脚本文件上使用它,您可以简单地 read 将其作为文本文件,例如:

#dir is the directory of a.py
#a.py, for example, contains the variable 'x=1'
exec(open(dir+'\a.py').read())
print(x) #outputs 1