在python中调用外部命令,python调用外部命令,在python中有很多办
在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")
相关内容
- Python内存调优,python调优,在python中可以使用
- 查询关键词在百度排名python脚本分享,python脚本,如下脚
- python 的IO文件操作总结,,在项目开发过程中,时常需
- Python如何查看变量占用空间大小,python变量占用空间
- error: 2006 MySQL server has gone away 解决方法,mysqlgone,今天在
- python使用正则表达式验证Email地址,pythonemail,下面的代
- 使用socket模块验证ip地址,socket模块验证ip,如下代码:
- python验证IP地址方法,python验证ip,可以使用socket模块
- python mutiprocessing 入门示例,,multiprocess
- Python 的多进程 fork,python进程fork,using_fork.p
评论关闭