在 Python 中通过用户输入访问子进程的输出
在 Python 中,您可以利用 subprocess 模块来执行外部脚本。然而,当调用提示用户输入的脚本时,在调用脚本中获取其输出可能具有挑战性。本文探讨了此问题的解决方案。
解决方案 1:将 check_output() 与输入结合使用
subprocess.check_output() 函数允许您运行脚本并捕获它的输出。要将输入传递给脚本,请使用输入参数:
<code class="python">import os import subprocess # Get script directory script_path = os.path.join(os.getcwd(), 'a.py') # Execute the script and capture output output = subprocess.check_output([sys.executable, script_path], input='\n'.join(['query 1', 'query 2']), universal_newlines=True)</code>
解决方案 2:模块导入和函数调用
另一种方法是导入脚本模块并调用特定函数:
<code class="python">import a results = [a.search(query) for query in ['query 1', 'query 2']]</code>
确保导入的脚本使用 if __name__ == "__main__": 保护以防止其代码在导入时执行。
解决方案3:多处理
如果查询处理是CPU密集型的,您可以通过使用多处理并行执行来提高性能:
<code class="python">from multiprocessing import freeze_support, Pool import a freeze_support() pool = Pool() # Use all available CPUs results = pool.map(a.search, ['query 1', 'query 2'])</code>
以上是以下是一些适合您文章内容的问题式标题: * 如何在 Python 中使用用户输入捕获子进程的输出? * 从需要用户 I 的子流程中获取输出的详细内容。更多信息请关注PHP中文网其他相关文章!