使用subprocess.Popen顺序执行Python脚本

0 投票
1 回答
563 浏览
提问于 2025-04-18 18:01

我正在使用Python的subprocess模块来执行一些脚本,这些脚本是针对一个C语言代码库的。具体来说,我有几个脚本需要一个接一个地运行,都是针对同一个程序实例。以下是我想做的事情:

start process ABC

execute python scripts 01 against ABC and store output from ABC in file A

execute python scripts 02 against ABC and store output from ABC in file B

execute python scripts 03 against ABC and store output from ABC in file C

我现在的做法是:

myProcess = subprocess.Popen(PATH, BUFFSIZE, STDOUT= myFilePointer ...)

但是这样做并不能从每次执行的过程ABC中获取返回输出,只记录了脚本01的输出,其他的输出都没有记录。

我查看了官方文档和其他一些资源,但找不到解决办法。

1 个回答

0

试试这个:

 cmd = subprocess.Popen("ABC %s" % command,
                    stdout=out,
                    stderr=subprocess.PIPE)
 stdout, stderr = cmd.communicate()
 retcode = cmd.returncode

使用 command 参数来传递命令行参数给 ABC。执行 Popen 后,ABC 的输出会保存在 stdout 中。如果出现错误,这些错误会被保存在 stderr 中。

撰写回答