以下是一些适合您文章内容的问题式标题: * 如何在 Python 中使用用户输入捕获子进程的输出? * 从需要用户 I 的子流程中获取输出

DDD
发布: 2024-10-27 03:04:03
原创
791 人浏览过

Here are a few question-style titles that fit the content of your article:

* How to Capture Output from a Subprocess with User Input in Python? 
* Getting Output from Subprocesses That Require User Input in Python: A Guide
* Interacting with Subprocesses

在 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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!