简体   繁体   English

使用子进程在python脚本中输入内容来调用python脚本

[英]Calling a python script with input within a python script using subprocess

I have a script a.py and while executing it will ask certain queries to user and frame the output in json format. 我有一个脚本a.py ,执行该脚本时会询问某些查询,以json格式对输出进行框架化。 Using python subprocess, I am able to call this script from another script named b.py . 使用python子b.py ,我可以从另一个名为b.py脚本中调用此脚本。 Everything is working as expected except that I am not able to get the output in a variable? 一切都按预期工作,除了我无法在变量中获取输出? I am doing this in Python 3. 我正在Python 3中执行此操作。

To call a Python script from another one using subprocess module and to pass it some input and to get its output: 要使用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)

where get_script_dir() function is defined here . 此处定义了get_script_dir()函数

A more flexible alternative is to import module a and to call a function, to get the result (make sure a.py uses if __name__=="__main__" guard, to avoid running undesirable code on import): 更为灵活的替代方法是导入模块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']]

You could use mutliprocessing to run each query in a separate process (if performing a query is CPU-intensive then it might improve time performance): 您可以使用mutliprocessing在单独的进程中运行每个查询(如果执行查询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'])

Another way than mentioned, is by using the built-in funtion exec 除了提到的之外,另一种方法是使用内置的函数exec
This function gets a string of python code and executes it 此函数获取一串python代码并执行它
To use it on a script file, you can simply read it as a text file, as such: 要在脚本文件上使用它,您可以简单地readread为文本文件,如下所示:

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM