Search code examples
python-2.7subprocesspopennonetype

python subprocess popen returns None


I have a python snippet like this:

self.task = subprocess.Popen("bash ./FOLDER/script.sh", cwd=some_dir, shell=True)
self.task.wait()

from which an exception is raised, complaining that a 'NoneType' object has no method wait(). I guess it means the Popen call returns None ? What could be the reason for that. The documentation does not mention this possibility

I'm using python 2.7.13


Solution

  • Well, apparently self.task gives a NoneType respons meaning the subprocess.Popen() command is likely at fault.

    First thing I notice is an incorrect syntax, since you did not wrap your command line in square brackets [] and you did not split the arguments.

    Furthermore, the Python docs state (regarding the cwd option you used):

    If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

    So first thing to check would be if your script.sh is situated in some_dir/FOLDER/script.sh.

    If that is indeed the case, please check if you inserted the cwd-argument with the right syntax, so as a string.. Meaning cwd="/path/to/some/dir".

    Then, since the Python docs clearly state that:

    Using shell=True can be a security hazard

    I would remove that argument. This might mean you will have to use the full path to your bash. To find out the correct path, open a terminal and execute which bash. Or, to be sure, type bash.

    Then, give this a try:

    import subprocess
    
    self.task = subprocess.Popen(["/path/to/your/bash", "./FOLDER/script.sh"], cwd="/path/to/some_dir", stdout=subprocess.PIPE, stderr=subprocess.PIPE) # This makes sure you will also catch any standard errors, so it allows for a bit more control. 
    output, errors = self.task.communicate() # This already encapsulates .wait()
    print(output.decode()) # if you'd like to check the output. 
    

    Read the comments in code for some further explanation..