5

I have an Electron app xxx.exe which is spawning an executable created from PyInstaller yyy.exe. In, yyy.exe, I am finally trying to launch a git cmd via subprocess.check_output(). Sadly, the call to check_output() throws [WinError 6] The handle is invalid.

If yyy.exe is directly launched on the command line, everything is running fine. The issue is only happening on Windows. My assumption is that there are some checks on stdin that trigger the exception because running through an Electron app doesn't provide any Stdin.

Any hints would be appreciated! Thanks in advance!

Pascal Gula
  • 1,143
  • 1
  • 8
  • 18

1 Answers1

8

On Windows, subprocess.Popen tries to duplicate non-zero standard handles and fails if they're invalid. You can redirect stdin and stderr to NUL. For example:

import os

try:
    from subprocess import DEVNULL
except ImportError:
    DEVNULL = os.open(os.devnull, os.O_RDWR)

output = subprocess.check_output(cmd, stdin=DEVNULL, stderr=DEVNULL)
Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
  • Plase make sure that you close the file handler DEVNULL after opening. – Astitva Srivastava Jun 24 '19 at 06:57
  • @AstitvaSrivastava, I intended for the `DEVNULL` file descriptor to be left open and reused for the life of a Python 2 process. If this is being used in a library, then it might be better to close it via `if not hasattr(subprocess, "DEVNULL"): os.close(DEVNULL)`, but not necessarily since consuming a single file descriptor is not a practical problem, especially if it's documented. – Eryk Sun Jun 24 '19 at 19:40
  • I did you use your method in a multithreaded application where a polling (discovery of disks) is done by executing a command using check_output. After certain discoveries, I was getting "Too Many Files Open" error. @eryksun – Astitva Srivastava Jun 25 '19 at 09:18
  • 2
    @AstitvaSrivastava, again, I intended for `DEVNULL` to be a global constant at module level in Python 2. I didn't write a function that would open `os.devnull` every time it's called. If you're doing that, then the file descriptor needs to be closed, and call `check_output` in a try-finally that guarantees `os.close` is called in the `finally` block. – Eryk Sun Jun 25 '19 at 09:44
  • Yes, I misunderstood it. Thanks. @eryksun – Astitva Srivastava Jun 26 '19 at 09:20
  • NameError: name 'cmd' is not defined –  Sep 07 '20 at 08:47
  • @AlexZab, `cmd` is the argument list or command-line string that you're trying to execute. The value is up to you. – Eryk Sun Sep 07 '20 at 08:57
  • I know) I have almost the same problem, and can not resolve it( https://stackoverflow.com/questions/63766452/oserror-winerror-6-the-handle-is-invalid-in-pysimplegui-while-using-w-in –  Sep 07 '20 at 09:21