0
votes

I'm working on windows vista, but I'm running python from DOS command. I have this simple python program. (It's actually one py file named test.py)

import os
os.system('cd ..')

When I execute "python test.py" from a Dos command, it doesn't work. For example, if the prompt Dos Command before execution was this:

C:\Directory>

After execution, must be this:

C:\>

Help Plz.

2
possible duplicate of How do I "cd" in python - Mat
What is the error? What doesn't it do? - Keith
What you do starts an external program that changes its own directory, then exits. It has no influence on the python process itself. - Mat
How can I change the path and see the immediate effect on the Dos Command? Is it possible? - Academia
if changing the CWD is what you want, you can just do os.chdir('..') - Not_a_Golfer

2 Answers

5
votes

First, you generally don't want to use os.system - take a look at the subprocess module instead. But, that won't solve your immediate problem (just some you might have down the track) - the actual reason cd won't work is because it changes the working directory of the subprocess, and doesn't affect the process Python is running in - to do that, use os.chdir.

0
votes

I don't really use Windows, but you can try cmd /k yourcommandhere. This executes the command and then returns to the CMD prompt. So for example, maybe you can do what you want like this:

subprocess.call(['cmd', '/k', 'cd .. &&  prompt changed'])

As I said, I am not familiar with Windows, so the syntax could be wrong, but you should get the idea.

In case you don't know, this is a different CMD instance than the one you were in before you started your python script. So when you exit, your python script should continue execution, and after it's done, you'll be back to your original CMD.