以下是一些适合文章内容并使用问题格式的标题选项: 选项1(聚焦问题): * 如何从使用'subprocess”调用的 Python 脚本获取输出? 奥普蒂奥

DDD
发布: 2024-10-25 21:29:03
原创
490 人浏览过

Here are a few title options that fit the article's content and use a question format:

Option 1 (Focus on the problem):

* How Can I Get Output From a Python Script Called Using `subprocess`?

Option 2 (Highlights the solution):

* Retrieving Output fro

使用 Subprocess 使用另一个脚本的输入调用 Python 脚本

在 Python 中,subprocess 模块提供了一种执行外部命令或脚本的方法。但是,当从另一个脚本调用 Python 脚本并向其提供输入时,获取输出可能具有挑战性。

从子进程调用获取输出

检索输出在子进程调用中,您可以使用 check_output 函数,该函数捕获外部脚本的标准输出。以下是实现此目的的方法:

<code class="python">import subprocess

# Path to the external script (a.py)
script_path = 'a.py'

# Input to be provided to the external script
input_data = '\n'.join(['query 1', 'query 2'])

# Execute the external script with input
output = subprocess.check_output([sys.executable, script_path],
                                 input=input_data,
                                 universal_newlines=True)</code>
登录后复制

在此示例中,input_data 是包含 a.py 的输入查询的字符串。 check_output 函数执行外部脚本,以标准输入形式提供输入查询。返回的输出变量现在包含脚本的字符串输出。

替代方法

除了直接使用 subprocess 模块之外,还有其他方法可以从内部调用 Python 脚本脚本:

  • 导入模块: 您可以将外部脚本导入到主脚本中并直接调用其函数。这需要在 a.py 中进行适当的模块级保护。
  • 使用多重处理:如果查询的计算成本很高,您可以使用多重处理在单独的进程中执行它们,从而可能提高性能。

以上是以下是一些适合文章内容并使用问题格式的标题选项: 选项1(聚焦问题): * 如何从使用'subprocess”调用的 Python 脚本获取输出? 奥普蒂奥的详细内容。更多信息请关注PHP中文网其他相关文章!

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