subprocess.run 在将 pyinstaller 与 --noconsole --onefile 一起使用时无法正常工作

subprocess.run isn't working while using pyinstaller with --noconsole --onefile

我正在使用 Pyinstaller 3.6、Python 3.8.3,当我编译这段代码时(使用标志 --onefile):

import subprocess

try:
    output = subprocess.run('dir', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    toWrite = output.stdout.decode('ansi')

    f = open('output.txt', 'w')
    f.write(toWrite)
    f.close()
except Exception as e:
    f = open('output.txt', 'w')
    f.write(str(e))
    f.close()

exit(0)

一切正常。这是 output.txt 文件:

 Volume in drive C has no label.

 Volume Serial Number is E612-C89D

 Directory of C:\Users\trolo\OneDrive\Desktop\progs\tests\dist

14.07.2020  12:11    <DIR>          .
14.07.2020  12:11    <DIR>          ..
14.07.2020  11:58         9я777я078 test3.exe

               1 File(s)      9я777я078 bytes
               2 Dir(s)  12я544я409я600 bytes free

但是当我添加标志 --noconsole 时,我在 output.txt 文件中得到了这个:

[WinError 6] The handle is invalid

出了什么问题,如何在不显示控制台的情况下使其工作 window?

python 3:你可以简单地通过 stdin=subprocess.DEVNULL

subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)

Python 2.x:您需要将文件处理程序设置为 null,然后将其传递给 popen

devnull = open(os.devnull, 'wb')
subprocess.Popen( args=[self.exec_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=devnull)