How to run commands on shell through python

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

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:

  • Python official documentation on os.system()
  • Python official documentation on the subprocess module

  • If you want more control over the called shell command (ie access to stdin and/or stdout pipes or starting it asynchronously), you can use the subprocess module:

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

    See also subprocess module documentation.


    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

    链接地址: http://www.djcxy.com/p/13494.html

    上一篇: 在python3中执行终端命令

    下一篇: 如何通过python在shell上运行命令