gxpr
gxpr

Reputation: 856

subprocess.Popen and relative directories

I am writing a script to open notepad.exe using subprocess.Popen()

import subprocess 
command = '%windir%\system32\\notepad.exe'
process = subprocess.Popen(command)
output = process.communicate()
print(output[0])

This throws a FileNotFoundError

Is it possible to change/add to the above code to make it work with relative paths? I did try to run the script from C:\Windows> after moving it there, which again failed. Also set the shell=True, but failed as well. Writing a similar script using os.popen() works ok with relative paths, regardless which directory the script is run from, but as far as I understand popen is not the way forward..

Early steps in the world of programming/Python. Any input much appreciated.

Upvotes: 1

Views: 1385

Answers (3)

Waxrat
Waxrat

Reputation: 2185

You could use raw strings to avoid having to double-up your backslashes.

command = r'%windir%\system32\notepad.exe'

Upvotes: 0

Dan D.
Dan D.

Reputation: 74655

Use os.path.expandvars to expand %windir%:

command = os.path.expandvars('%windir%\\system32\\notepad.exe')

The result is a path that then can be passed to subprocess.Popen.

subprocess.Popen does not expand environment variables such as %windir%. The shell might but you really should not depend on shell=True to do that.

Upvotes: 1

James K. Lowden
James K. Lowden

Reputation: 7837

Pro tip: whenever you get an error asking the system to execute a command, print the command (and, if applicable, the current working directory). The results will often surprise you.

In your case, I suspect you're just missing a backslash. Use this instead:

command = '%windir%\\system32\\notepad.exe'

Before you make that change, try printing the value of command immediately after assignment. I think you'll find the leading "s" in "system" is missing, and that the mistake is obvious.

HTH.

Upvotes: 1

Related Questions