设为首页 收藏本站
查看: 883|回复: 0

python执行shell命令

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-11-30 14:41:35 | 显示全部楼层 |阅读模式
  1 os.system
  可以返回运行shell命令状态,同时会在终端输出运行结果
  例如 ipython中运行如下命令,返回运行状态status



os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0
  
  2 os.popen()
  可以返回运行结果



popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
  运行返回结果



In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
lineLen.append(len(line))
....:     
In [23]: line
line     lineLen  
In [23]: lineLen
Out[23]:
[14,
25,
...
  
  3 如何同时返回结果和运行状态,commands模块:



#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"

A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
  commands示例如下:



In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859
  
  4 使用模块subprocess
  ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块



A more real-world example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
  相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:
  4.1.1 subprocess.call()
  父进程父进程等待子进程完成,返回exit code
  4.1.2 subprocess.check_call()
  父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查
  4.1.3 subprocess.check_output()
  父进程等待子进程完成
  返回子进程向标准输出的输出结果
  检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查
  例如:



In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--.  1 *** ***     366 May 26 09:10 ChangeLog
  4.2.1
  上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数
  Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)



[wenwt@localhost syntax]$ rm subprocess.pyc
[wenwt@localhost syntax]$ python process.py
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
  加上wait方法:



[wenwt@localhost syntax]$ python process.py
PING www.google.com (173.194.219.103) 56(84) bytes of data.
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
parent process
  
  参考文章:Python标准库06 子进程 (subprocess包)
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145469-1-1.html 上篇帖子: shell 脚本查看网段ip使用情况 下篇帖子: python文件读写操作与linux shell变量命令交互执行
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表