使用Pyinstaller进行Python子进程Popen操作

5
我使用ffmpeg来转换一些视频。 我用subprocess.Popen(...)命令调用它。
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

self.my_pro = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=si)

(output, error) = self.my_pro.communicate()

我使用这种方法进行杀戮

self.my_pro.kill()

无需编译成exe也可以。

但是我使用pyinstaller编译并加上--noconsole后,子进程不起作用。 我必须将subprocess.Popen(...)更改为subprocess.check_output(...)

但这次我无法使用self.my_pro.kill()来结束进程,这个方法不起作用。

我该如何运行进程以便能够杀死它,并且它会运行带有pyinstaller的noconsole?


如果 check_output() 能够正常工作,但是 Popen() + .communicate() 无法正常工作,那么问题很可能出在使用 Popen() 的代码上,因为 check_output() 在内部是基于 Popen() 实现的。你尝试过重定向所有内容(stdin、stderr、stdout)了吗? - jfs
1个回答

3

正如 @jfs 所写,使用 Popen 时您必须重定向所有内容。您忘记了 stdout

因此这段代码对我来说不再崩溃:

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

self.my_pro = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
startupinfo=si)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接