0

Im trying to use python to run cmd.exe and thereby running commands like cd C:\name..... and executing other programs from the cmd what I have so far is.

os.system("cmd.exe").
os.system("cd C:\name\first\second").

When I try to run three other commands a new cmd window replaces the old one and the commands dont work since they need to be consecutively after each other.I already tried the above code and need help running the next three. Also can you explain what suproccess are.

user3754017
  • 75
  • 1
  • 7
  • This may be a workaround, but instead of using "cd", why don't you just do `os.system("C:\name\first\second\cmd.exe") etc. – James Jun 18 '14 at 20:02
  • Depends a bit on what exactly you want to achieve, but have a look at this answer: http://stackoverflow.com/questions/89228/calling-an-external-command-in-python/89243#89243 – Dirk Jun 18 '14 at 20:03
  • It's unclear exactly what you mean by this, "... the commands dont work since they need to be consecutively after each other," since you are quite literally running the commands one after the other. For why `cd` specifically doesn't work see my answer below. – Dan Lenski Jun 18 '14 at 20:07

1 Answers1

2

See my answer to this recent question for why os.system("cd WHEREVER") does not do what you expect.

Briefly, when you run os.system('cd WHEREVER') you are creating a new command shell which has its own idea of the current directory. This change in the current directory will be entirely "forgotten" on subsequent calls to os.system(). You need to change the current directory in the parent process (the script) with os.chdir('WHEREVER') in order to retain the change for subsequent os.system() calls.

Community
  • 1
  • 1
Dan Lenski
  • 76,929
  • 13
  • 76
  • 124
  • Did you read my answer and the examples from the other question? – Dan Lenski Jun 19 '14 at 15:06
  • What do you mean "the `for` loop"? If you have a question about that specific example, add a comment there. – Dan Lenski Jun 19 '14 at 15:37
  • Besides changing the directory is there any way to keep the current command line while passing arguments with python – user3754017 Jun 19 '14 at 15:46
  • I don't know what "keep the current command line" means either. As suggested above, you should post a *complete* example, explain what it is trying to do, and what it actually does. – Dan Lenski Jun 19 '14 at 15:48
  • When you use os.system you open a new command shell each time so is there a way to open the shell once and pass arguments later in python – user3754017 Jun 19 '14 at 15:52
  • Yes, but it's very dependent on the specific OS and shell you are using (try the [subprocess](https://docs.python.org/2/library/subprocess.html) module and learn how to open a pipe between your script and the shell). – Dan Lenski Jun 19 '14 at 16:06