0

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.

Academia
  • 3,984
  • 6
  • 32
  • 49

2 Answers2

5

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.

lvc
  • 34,233
  • 10
  • 73
  • 98
  • How can I change the path and see the immediate effect on the Dos Command? Is it possible? – Academia Jun 02 '12 at 12:37
  • 1
    @user1038382 it is hard to tell what you mean, but I *think* that `os.chdir(newworkingdir)` followed by `subprocess.call(['cmd'])` will do what you want. Changing Python's working directory will have a flow-on effect onto every subprocess you spawn after that point. – lvc Jun 02 '12 at 12:45
  • lvc, thks a lot. It works. Now I'm asking for something else, could this work (change the prompt Dos Command): os.system('prompt changed ') subprocess.call(['cmd'])? – Academia Jun 02 '12 at 13:00
  • 1
    @user1038382 not easily, or any way that I can think of or find. You can do that if `cmd` takes an argument for changing its prompt or looks at an environment variable (as the equivalents on \*nix tend to), but a brief search finds nothing suggesting that that is the case. Sending a command *into* an open `cmd` would work, but be nontrivial - even if `cmd` listens for commands on STDIN, Python doesn't currently have async IO in the stdlib. Invoking `prompt` as a subprocess won't work for the same reason that invoking `cd` as a subprocess won't work. So, if it is doable, it probably isn't easy. – lvc Jun 02 '12 at 13:18
0

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.

Amr
  • 695
  • 4
  • 11