专栏首页python3python调用外部命令

python调用外部命令

python调用外部命令

os.system:  输出在终端上,捕捉不到

os.popen:  只能捕捉到标准输出,捕捉不到标准错误输出

os.popen2: 返回2个对象,一个是标准输入,一个是标准输出

os.popen3: 返回3个对象,标准输入,标准输出,标准错误输出

os.popen4: 返回2个对象,pip_in 和pip_out_err

os.system:  输出在终端上,捕捉不到

In [4]: os.system('ls')                                                                                                                                                            
13001195917  1_md5.py  1_walk.py  2.txt  ErrorExcept.py  hashlib2.py  test  top10.py  walk1.py  yield1.py  yield2.py  非码+支付宝会员_喜欢牛肉_手机号码.txt                        
Out[4]: 0  

In [6]: s = os.system('ls')                                                                                                                                                        
13001195917  1_md5.py  1_walk.py  2.txt  ErrorExcept.py  hashlib2.py  test  top10.py  walk1.py  yield1.py  yield2.py  非码+支付宝会员_喜欢牛肉_手机号码.txt                        

In [7]: s                                                                                                                                                                          
Out[7]: 0     #echo $? 返回值为0,                                                                                                                                                                     

In [9]: s = os.system('ls a')                                                                                                                                                      
ls: 无法访问a: 没有那个文件或目录                                                                                                                                                  

In [10]: s                                                                                                                                                                         
Out[10]: 512  #echo $? 返回值为512

os.popen:  只能捕捉到标准输出,捕捉不到标准错误输出

In [12]: out = os.popen('ls')                                                                                                                                                      
                                                                                                                                                                                   
In [13]: out.read()                                                                                                                                                                
Out[13]: '13001195917\n1_md5.py\n1_walk.py\n2.txt\nErrorExcept.py\nhashlib2.py\ntest\ntop10.py\nwalk1.py\nyield1.py\nyield2.py\n\xe9\x9d\x9e\xe7\xa0\x81+\xe6\x94\xaf\xe4\xbb\x98\x
e5\xae\x9d\xe4\xbc\x9a\xe5\x91\x98_\xe5\x96\x9c\xe6\xac\xa2\xe7\x89\x9b\xe8\x82\x89_\xe6\x89\x8b\xe6\x9c\xba\xe5\x8f\xb7\xe7\xa0\x81.txt\n'

os.popen2: 返回2个对象,一个是标准输入,一个是标准输出

In [23]: stdin, stdout = os.popen2('sort')                                                                                                                                         
/usr/local/bin/ipython:1: DeprecationWarning: os.popen2 is deprecated.  Use the subprocess module.                                                                                 
  #!/usr/local/bin/python2.7

In [24]: stdin.write('hello')     #stdin输入hello                                                                                                                                                 
                                                                                                                                                                                   
In [25]: stdin.write('world')                                                                                                                                                      
                                                                                                                                                                                   
In [26]: stdin.write('abc\n')                                                                                                                                                      
                                                                                                                                                                                   
In [27]: stdin.write('123\n')                                                                                                                                                      
                                                                                                                                                                                   
In [28]: stdin.close()                                                                                                                                                             
                                                                                                                                                                                   
In [29]: stdout.read()         #stdout.read()会把stdin()的标准输入排序输出                                                                                                                                                       
Out[29]: '123\nhelloworldabc\n'

os.popen3: 返回3个对象,标准输入,标准输出,标准错误输出

In [33]: stdin, stdout, stderr = os.popen3('ls a')                                                                                                                                 
/usr/local/bin/ipython:1: DeprecationWarning: os.popen3 is deprecated.  Use the subprocess module.                                                                                 
  #!/usr/local/bin/python2.7

In [34]: stderr.read()      #执行stderr报错                                                                                                                                                       
Out[34]: 'ls: \xe6\x97\xa0\xe6\xb3\x95\xe8\xae\xbf\xe9\x97\xaea: \xe6\xb2\xa1\xe6\x9c\x89\xe9\x82\xa3\xe4\xb8\xaa\xe6\x96\x87\xe4\xbb\xb6\xe6\x88\x96\xe7\x9b\xae\xe5\xbd\x95\n'

os.popen4: 返回2个对象,pip_in 和pip_out_err(标准输出和标准错误输出保存到一个输出pip_out_err)

subprocess模块

In [43]: import subprocess  
In [50]: subprocess.call(['ls abcd.txt'])
OSError: [Errno 2] No such file or directory    

In [10]: subprocess.call(['ls -l'])  #会把-l当成一个文件,找不到该文件
OSError: [Errno 2] No such file or directory    
 
In [49]: subprocess.call(['ls -l'],shell = True)  #默认shell=False ,shell=True,表示执行ls -l命令                                                                                                                                
总用量 2888                                                                                                                                                                        
-rw-r--r-- 1 root root      12 12月  6 19:50 13001195917
-rw-r--r-- 1 root root     453 12月  6 19:31 1_md5.py
-rw-r--r-- 1 root root     453 12月  2 16:48 1_walk.py
-rw-r--r-- 1 root root      14 12月  6 16:42 2.txt

In [51]: help(subprocess.call) 
call(*popenargs, **kwargs)     #表示接受冗余参数

In [54]: subprocess.call(['ls','-l'])   #或者写入列表中                                                                                                                                           
总用量 2888                                                                                                                                                                        
-rw-r--r-- 1 root root      12 12月  6 19:50 13001195917
-rw-r--r-- 1 root root     453 12月  6 19:31 1_md5.py
-rw-r--r-- 1 root root     453 12月  2 16:48 1_walk.py
-rw-r--r-- 1 root root      14 12月  6 16:42 2.txt
In [58]: a=subprocess.check_call(['ls','-l'])                                                                                                                                      
总用量 2888                                                                                                                                                                        
-rw-r--r-- 1 root root      12 12月  6 19:50 13001195917
-rw-r--r-- 1 root root     453 12月  6 19:31 1_md5.py
-rw-r--r-- 1 root root     453 12月  2 16:48 1_walk.py
-rw-r--r-- 1 root root      14 12月  6 16:42 2.txt
-rw-r--r-- 1 root root     412 12月  7 20:25 ErrorExcept.py
-rw-r--r-- 1 root root     425 10月 24 05:57 hashlib2.py
drwxr-xr-x 2 root root    4096 10月 24 06:03 test
-rw-r--r-- 1 root root     556 12月  6 16:06 top10.py
-rw-r--r-- 1 root root     430 10月 25 21:56 walk1.py
-rw-r--r-- 1 root root     128 10月 25 18:07 yield1.py
-rw-r--r-- 1 root root     680 10月 25 21:27 yield2.py
-rw-r--r-- 1 root root 2910024 12月  6 16:48 非码+支付宝会员_喜欢牛肉_手机号码.txt

In [59]: a                                                                                                                                                                         
Out[59]: 0    

In [62]: a=subprocess.check_call(['ls','a'])    #抛出异常                                                                                                                                   
ls: 无法访问a: 没有那个文件或目录   
---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-62-575484aab70a> in <module>()
----> 1 a=subprocess.check_call(['ls','a'])

/usr/local/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs)
    538         if cmd is None:
    539             cmd = popenargs[0]
--> 540         raise CalledProcessError(retcode, cmd)
    541     return 0
    542 

CalledProcessError: Command '['ls', 'a']' returned non-zero exit status 2
In [63]: a     #a的值还是0,并没有将异常的值保存到a中                                                                                                                                                                    
Out[63]: 0   

[root@133 systeminformation]# vim process_check_call.py 
#!/usr/bin/env python                                                                                                                                                              
#ecoding=utf8                                                                                                                                                                      
                                                                                                                                                                                   
import subprocess                                                                                                                                                                  
                                                                                                                                                                                   
                                                                                                                                                                                   
try:                                                                                                                                                                               
    subprocess.check_call('exit 1', shell = True)                                                                                                                                  
except Exception:                                                                                                                                                                  
    print "exit 1返回echo $?不是0,抛出异常,打印出来" 
[root@133 systeminformation]# python process_check_call.py
exit 1返回echo $?不是0,抛出异常,打印出来



#!/usr/bin/env python                                                                                                                                                              
#ecoding=utf8                                                                                                                                                                      
                                                                                                                                                                                   
import subprocess                                                                                                                                                                  
                                                                                                                                                                                   
                                                                                                                                                                                   
try:                                                                                                                                                                               
    subprocess.check_call('exit 1', shell = True)                                                                                                                                  
except subprocess.CalledProcessError:      #不知道异常名称,使用:except Exception:  表示接受所有异常处理                                                                                                                                        
    pass                                                                                                                                                                           
print "exit 1返回echo $?不是0,抛出异常,打印出来,捕捉到异常"     

[root@133 systeminformation]# python process_check_call.py
exit 1返回echo $?不是0,抛出异常,打印出来,捕捉到异常

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

推荐阅读

  • 「网安夜校」开课啦!多门网络安全课程开启限时优惠报名

    众志成城,共抗疫情。腾讯安全联合腾讯云大学、腾讯课堂启动「网安夜校」,为大家提供限时优惠的网络安全课程。欢迎网络安全从业者和信息安全专业学生报名参加学习,快速充电提升自我。

    腾讯安全
    安全培训腾讯云大学
  • Flink源码走读(一):Flink工程目录

    导语 | Flink已经成为未来流计算趋势,目前在很多大厂已经有了大规模的使用。最近在学习Flink源码,就想把自己学习的过程分享出来,希望能帮助到志同道合的朋友。开始阅读源码,说明读者已经对flink的基本概念有一些了解,这里就不再重复介绍Flink了。本文作为学习过程的第一章,首先对Flink的工程目录做一个解读,了解了工程下各个模块的作用,才能在遇到问题时准确定位到代码,进一步学习。

    2011aad
    大数据解决方案
  • Flink源码走读(二):Flink+Kafka实现端到端Exactly Once语义

    Flink通过Checkpoint机制实现了消息对状态影响的Exactly Once语义,即每条消息只会影响Flink内部状态有且只有一次。但无法保证输出到Sink中的数据不重复。以图一所示为例,Flink APP收到Source中的A消息,将其转化为B消息输出到Sink,APP在处理完A1后做了一次Checkpoint,假设APP在处理到A4时发生错误重启,APP将会重新从A2开始消费并处理数据,就会导致B2和B3重复输出到Sink中两次。

    2011aad
    大数据解决方案Kafka
  • kubernetes系列教程(十九)使用metric-server让HPA弹性伸缩愉快运行

    kubernetes监控指标大体可以分为两类:核心监控指标和自定义指标,核心监控指标是kubernetes内置稳定可靠监控指标,早期由heapster完成,现由metric-server实现;自定义指标用于实现核心指标的扩展,能够提供更丰富的指标支持,如应用状态指标,自定义指标需要通过Aggregator和k8s api集成,当前主流通过promethues实现。

    HappyLau谈云计算
    Kubernetes容器微服务微服务架构腾讯微服务平台 TFS
  • 三分钟入坑指北 🔜 Docsify + Serverless Framework 快速创建个人博客系统

    之前由于学摄影的关系,为了提高自己的审美,顺便锻炼下自己的英文能力,翻译了不少国外艺术类的 文章。最近一直想搭一个个人博客来存放这些内容,又懒得折腾建站,遂一直搁置。

    Aceyclee
    ServerlessHTML网站GitGitHub
  • NVM作为主存上对数据库管理系统的影响

    implications of non-volatile memory as primary storage for database management systems

    yzsDBA
    存储缓存数据库数据结构SQL
  • DevOps平台架构演进

    附最新架构图https://www.processon.com/view/5cbd897de4b0bab90962c435

    我思故我在
    DevOps 解决方案微服务架构架构设计
  • 【腾讯云AI小程序大赛】中山大学作品《小耳朵天使》

    ----------------------------------------------------------------------------------

    陈华山
    小程序 · 云开发小程序语音识别文字识别对话机器人
  • Kona JDK 在腾讯大数据领域内的实践与发展

    经常听人谈到 OpenJDK,那它到底是什么呢?相信大家都听说过 Java SE、ME、EE等规范, 通常意义上对 Open JDK 的定义指:Java SE规范的一个免费和开源参考实现。

    腾小云
    JDKJavaJVM大数据Oracle
  • 公告丨腾讯安全产品更名通知

    为了更好地为政企客户的安全保驾护航,腾讯安全即日起更新旗下身份安全、网络安全、终端安全、应用安全、数据安全、业务安全、安全管理、安全服务等八类安全产品的命名,致力于打造全栈安全产品“货架”,让客户选购安全产品/服务更加便捷,更快地找到合适的安全产品,从而对自身的安全建设“对症下药”。

    腾讯安全
    DDoS 防护应用安全 MS验证码(业务安全)应用安全(移动安全)漏洞扫描服务

扫码关注云+社区

领取腾讯云代金券