itz_lexiii_
itz_lexiii_

Reputation: 51

Python - Errno 2: No such file or directory

So, im trying to use subprocess.Popen() to open a python script in CMD the "complicated" way. Although I cant get it to open due to a space in my PC name. Ive tried using Double Quotes and Single Quotes vut it still doesn't work.

Heres the line of code im trying to execute.

subprocess.Popen("cmd.exe /C python '\Users\Terra Byte\Desktop\jdos3\JDOS3\SYS64\bootthingy.py'")

As you can see, I'm using single quotes to wrap the directory path, yet this is the error I get when executing.

C:\Users\Terra Byte\Desktop\jdos3\JDOS3>python: can't open file ''\Users\Terra': [Errno 2] No such file or directory

It seems to be completely ignoring my single quotes.

Upvotes: 2

Views: 1033

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

Never try to build your command name as a string.

In this particular case, be aware that single quotes have no protection effect on windows (unlike on Linux/Unix) which explains the quoting you've used is inefficient. Using double quotes would have worked, but it's not the best way.

Never use a string when you can pass the list of arguments. This will work:

subprocess.Popen(["python",r'\Users\Terra Byte\Desktop\jdos3\JDOS3\SYS64\bootthingy.py'])
  • use list of strings, unquoted, and let subprocess do the work
  • remove cmd /c prefix, as python prefix is enough (alternately, remove python to leave ["cmd","/c" and let file associations do the work)
  • use raw string prefix to avoid that backslashes are interpreted

Upvotes: 2

Related Questions