Python子进程获取输出

问题描述 投票:0回答:1

我有一个 python 脚本来使用 subprocess 模块运行辅助 python 脚本。 我想捕获第二个 python 脚本输出并在关闭主 python 脚本后使其保持活动状态。 我想等待第二个 python 脚本中的某个提示,然后停止主脚本的执行。 问题是我在循环中没有看到输出。

我的主要脚本:

command = f'start /D C:\MyFolder python adapter.py -t \"UMB\" -d \"COM2\"'
process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
while True:    
    output = process.stdout.readline()
    if output:
        print(output, end='')

另外,我需要第二个 python 脚本从其文件夹“MyFolder”运行 请帮忙,谢谢!

python subprocess stdout
1个回答
0
投票

您的代码中存在一些问题。

首先,start命令一般在Windows的命令提示符下使用,但在使用subprocess.Popen()时就不需要了。

其次,您应该使用 subprocess.Popen() 中的 cwd 参数设置工作目录。

我还建议您使用 stdout=subprocess.PIPE 来捕获子进程的输出。

如果这还不够帮助或需要澄清,请随时对此答案发表评论

© www.soinside.com 2019 - 2024. All rights reserved.