在python中调用外部命令,python调用外部命令,在python中有很多办


在python中有很多办法可以执行外部命令,做个总结

一. 使用subprocess模块的call方法

from subprocess import callcall(["ls", "-l"])

使用subprocess模块的好处是,程序以子进程的模式运行,可以捕获到进程的执行状态和返回的结果

二. 使用subprocess模块的Popen方法

from subprocess import Popen, PIPEcmd = "ls -l ~/"p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)out, err = p.communicate()print "Return code: ", p.returncodeprint out.rstrip(), err.rstrip()

或者使用下面的方法获得命令行执行返回的结果:

import subprocessp = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)for line in p.stdout.readlines():    print line,retval = p.wait()

上面的例子可以得到子进程执行的返回值和错误码。

三. 使用os.system

os.system("ls -l")

评论关闭