当前位置: 首页 > 后端技术 > Python

python执行shell命令的四种方式

时间:2023-03-25 22:38:39 Python

下面介绍python执行shell命令的四种方式:1.os模块中的os.system()函数执行shell命令>>>os.system('ls')anaconda-ks.cfginstall.loginstall.log.syslogsend_sms_service.pysms.py0注意,这个方法并没有得到shell命令的输出。2、popen()方法可以得到command执行后的结果为字符串,需要自己处理才能得到想要的信息。>>>importos>>>str=os.popen("ls").read()>>>a=str.split("\n")>>>forbina:printb中得到的结果这种方式和第一种方式一样。3、commands模块可以方便的获取命令的输出(包括标准输出和错误输出)和执行状态位importcommandssa,b=commands.getstatusoutput('ls')a是退出状态b是输出结果。>>>导入命令>>>a,b=commands.getstatusoutput('ls')>>>printa0>>>printbanaconda-ks.cfginstall.loginstall.log.syslogcommands.getstatusoutput(cmd)返回(状态,输出)commands.getoutput(cmd)只返回输出结果commands.getstatus(file)返回ls-ldfile的执行结果字符串,调用getoutput,不推荐这种方式。4.Subprocess模块??使用subprocess模块??创建新进程,连接新创建进程的输入/输出/错误管道,获取新创建进程执行的返回状态。使用subprocess模块的目的是替换旧的函数或模块,例如os.system()、os.popen()、commands.等。importsubprocesssubprocess.call(command,shell=True)会直接打印出结果。subprocess.Popen(command,shell=True)也可以是subprocess.Popen(command,stdout=subprocess.PIPE,shell=True)这样就可以输出结果了。如果command不是可执行文件,则不能省略shell=True。shell=True表示shell下执行command的四种方法都可以执行shell命令。