1

When writing a Python code, I could write os.system('some cmd command'). How could I make it run from a specific directory (without using a 'cd' command)?

The reason I'm trying to do this is because my cmd command isn't in my cmd PATH, and therefore is recognized only in its own directory.

I'm looking for something similar to this:

p = Popen ('file.bat', cwd = 'location')
stdout, stderr = p.communicate()

just without having to create a .bat file for it...

2
  • Assign the abs path to a variable and pass as an argument? I'm not sure if that's what you're going for. Commented Apr 30, 2014 at 19:13
  • Sorry @crownedzero, I didn't really understand your comment. What's an abs path and where should I pass it as an argument to? Commented Apr 30, 2014 at 19:15

1 Answer 1

3

You could always do:

p = Popen ('../relative/path/to/executable.exe')
stdout, stderr = p.communicate()

Or you could hard-code an absolute path in there, but be sure to check if the file exists first or to catch any exceptions thrown by the popen calls (more pythonic).

LE: Please note that there is a cwd parameter on the Popen's constructor, but the executed program's current directory will be changed to that, it won't look for the executable in there.

Sign up to request clarification or add additional context in comments.

5 Comments

I was going to go for this but I wasn't sure that's what they were trying to do :(
@Cheshie Yes, sure, there you could write whatever path you want. Not necessarily a bat file, just try it out. LE: I edited the post.
@Paul, can I write an actual command instead of the exe in your example?
Yes, but you'll have to specify shell=True as another argument for the Popen constructor. Be sure to read on why that might be a security issue if the command you're running comes from user input in the documentation of the subprocess module.
Also shell=True is needed only if the command is to be passed through the shell, from your original question I understand that your command is an executable script, which shouldn't require that, though this is only an assumption.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.