文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

python调用外部命令

2023-01-31 06:41

关注

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,抛出异常,打印出来,捕捉到异常





阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯