23

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
2

4 Answers 4

8

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:

1
  • os.system() will run in /bin/sh . If your command (script) requires bash, this won't work.
    – Ben L
    Commented Nov 9, 2022 at 21:30
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.

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

2
  • someone told me we have subprocess.call , os.system... which one is usefull??
    – mrutyunjay
    Commented Jan 22, 2013 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
    Commented Jan 22, 2013 at 11:49
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.