Search code examples
pythonpython-3.xsubprocessascii

'Errno 2 no such file or directory' Problem with white space in directory path while using subprocessing module Popen command


I have the following code that lets me run a .py file by using the subproccessing library

The code

import subprocess
process = subprocess.Popen('python C:/Users/Example User/Projects/file.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

output, error = process.communicate()
print('output')
print(output)
print('error')
print(error)

The problem

The issue I'm running into is that there is no output, and printing the error shows the following message : "c:/example/python/directory/python.exe can't open file 'C:\Users\Example': [Errno 2] No such file or directory\n" (this is the complete error I get in the terminal)

I figure the issue might have something to do with the fact that there's a whitespace since the rest of the directory doesn't show up but I might be completely wrong. If I have the file in my current directory, then the code works as long as I don't pass it the complete path address (i.e if I just give Popen ('python file.py' the code executes fine)

What I've tried

I have tried using (double backslashes) \\ , +' ', //, /, single \, I can't change the main directory on my work computer, but I tried using it on my personal pc and it works (no spaces in my directory). https://docs.python.org/3/library/subprocess.html the docs do mention that it should be formatted as it would be in the shell.

If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

any help and all suggestions would be appreciated, or if I can do anything to make the problem clearer


Solution

  • Your argument is splitted into two arguments. C:/Users/Example and User/Projects/file.py. Try:

    process = subprocess.Popen('python "C:/Users/Example User/Projects/file.py"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    

    The popen call is like a terminal call. To start a script you write python script.py. Whitespace is used as a separator between arguments. If you specify an absolute path and a folder contains a space in the name, two arguments are recognized e.g. python c:/folder name/script.py. Argument one is c:/folder and argument two is name/script.py. To avoid this the argument must be placed in "": python "c:/folder name/script.py".