pythonsubprocesspopenoserror

OSError: [WinError 6] The handle is invalid


I'm trying to run following function where path parameter is path to my script. But I get OSError: [WinError 6] The handle is invalid.

I have seen solutions by adding stdin=subprocess.DEVNULL but it still doesn't work.

My function:

import subprocess

def run_python_script(path: str):
    
    return_value = subprocess.Popen(args=[path,], stdin=subprocess.DEVNULL)
    time.sleep(3)
    if return_value.returncode is None:
        return 1, "Script run correctly"
    else:
        return 0, f"Error occured while running script - [Errno {return_value.returncode}]"

Full error:

[2022-08-23 13:56:27] Exception ignored in: <function Popen.__del__ at 0x000001E32DA28B80>
Traceback (most recent call last):
  File "C:\Python\Python310\lib\subprocess.py", line 1070, in __del__
    self._internal_poll(_deadstate=_maxsize)
  File "C:\Python\Python310\lib\subprocess.py", line 1472, in _internal_poll
    if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
OSError: [WinError 6] The handle is invalid
Exception ignored in: <function Handle.Close at 0x000001E32D7FBD90>
Traceback (most recent call last):
  File "C:\Python\Python310\lib\subprocess.py", line 199, in Close
    CloseHandle(self)
OSError: [WinError 6] The handle is invalid

Solution

  • If you just want to get the return code of your script, try using subprocess.call instead. If you want to call a python script with subprocess, you need to point to the interpreter too (assuming its is just "python" for you)

    def run_python_script(path: str):
        return_value = subprocess.call(args=["python", path])
        if return_value == 0:
            return 1, "Script run correctly"
        else:
            return 0, f"Error occured while running script - [Errno {return_value}]"
    

    As a rule of thumb, use subprocess.Popen only if you have to and try use builtin wrappers instead, such as subprocess.run.

    You could also consider using runpy