20

Possible Duplicate:
Calling an external command in Python

I want to run commands in another directory using python.

What are the various ways used for this and which is the most efficient one?

What I want to do is as follows,

cd dir1
execute some commands
return 
cd dir2
execute some commands
hygull
  • 7,072
  • 2
  • 35
  • 42
mrutyunjay
  • 4,840
  • 5
  • 22
  • 34

4 Answers4

5

Naturally if you only want to run a (simple) command on the shell via python, you do it via the system function of the os module. For instance:

import os
os.system('touch myfile')

If you would want something more sophisticated that allows for even greater control over the execution of the command, go ahead and use the subprocess module that others here have suggested.

For further information, follow these links:

NlightNFotis
  • 8,829
  • 5
  • 39
  • 62
4

If you want more control over the called shell command (i.e. access to stdin and/or stdout pipes or starting it asynchronously), you can use the subprocessmodule:

import subprocess

p = subprocess.Popen('ls -al', shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()

See also subprocess module documentation.

helmbert
  • 28,771
  • 10
  • 73
  • 74
1
os.system("/dir/to/executeble/COMMAND")

for example

os.system("/usr/bin/ping www.google.com")

if ping program is located in "/usr/bin"

Naturally you need to import the os module.

os.system does not wait for any output, if you want output, you should use

subprocess.call or something like that

Gjordis
  • 2,340
  • 1
  • 19
  • 29
  • someone told me we have subprocess.call , os.system... which one is usefull?? – mrutyunjay Jan 22 '13 at 11:47
  • Depending on what you need. If you want to just start something in the shell in the back, use os.system. Use subprocess.call or something similar if you want to wait for the results from the process.. subprocess.Popen, works quite similarly as popen in c – Gjordis Jan 22 '13 at 11:49
0

You can use Python Subprocess ,which offers many modules to execute commands, checking outputs and receive error messages etc.

FallenAngel
  • 15,966
  • 10
  • 78
  • 105