0
点赞
收藏
分享

微信扫一扫

python执行shell的两种方法

西曲风 2023-02-07 阅读 106


有两种方法可以在Python中执行SHELL程序,方法一是使用Python的commands包,方法二则是使用subprocess包,这两个包均是Python现有的内置模块。

使用python内置commands模块执行shell

commands对Python的​​os.popen()​​进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态;

该命令目前已经废弃,被subprocess所替代;

Python

# coding=utf-8
'''
Created on 2013年11月22日

@author: crazyant.net
'''
import commands
import pprint

def cmd_exe ( cmd_String ) :
print "will exe cmd,cmd:" + cmd_String
return commands . getstatusoutput ( cmd_String )

if __name__ == "__main__" :
pprint . pprint ( cmd_exe ( "ls -la" ) )




使用python最新的subprocess模块执行shell

Python目前已经废弃了os.system,os.spawn*,os.popen*,popen2.*,commands.*来执行其他语言的命令,subprocesss是被推荐的方法;

subprocess允许你能创建很多子进程,创建的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。

# coding=utf-8
'''
Created on 2013年11月22日

@author: crazyant.net
'''
import commands
import pprint

def cmd_exe ( cmd_String ) :
print "will exe cmd,cmd:" + cmd_String
return commands . getstatusoutput ( cmd_String )

if __name__ == "__main__" :
pprint . pprint ( cmd_exe ( "ls -la" ) )

也可以在Popen中指定stdin和stdout为一个变量,这样就能直接接收该输出变量值。

总结

在python中执行SHELL有时候也是很必须的,比如使用Python的线程机制启动不同的shell进程,目前subprocess是Python官方推荐的方法,其支持的功能也是最多的,推荐大家使用。


举报

相关推荐

0 条评论