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   

[[email protected] 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,抛出异常,打印出来" 
[[email protected] 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,抛出异常,打印出来,捕捉到异常"     

[[email protected] systeminformation]# python process_check_call.py
exit 1返回echo $?不是0,抛出异常,打印出来,捕捉到异常
时间: 2024-10-06 14:47:00

python调用外部命令的相关文章

Python 调用外部命令

python 可以使用 os 模块来调用外部的 Linux Shell 命令,常用的方法如下: (1) os.system():结果输出在终端上,捕获不到(2) os.popen() : 结果返回一个对象,即标准输出(3) os.popen2():结果返回两个对象,分别是标准输入,标准输出(4) os.popen3():结果返回三个对象,分别是标准输入,标准输出,标准错误输出(5) os.popen4():结果返回两个对象,分别是标准输入,标准输出(标准输出中包括标准错误输出) In [2]:

关于调用外部命令时与外部命令的数据交互的注意点

前两天,我打算下载点图片.用fiddler分析了下,结果那个网页大量使用js来操作cookie,弄得我头大. go倒是有V8引擎的封装包,可是必须还得编译这个引擎,挺麻烦的. 想起来还有selenium-python可以用.就决定这个了.因为selenium没有python3.4的版本,不得不重装了python2.7. 多说一句,python3确实比python2的组织等各个方面改进很多,写起来感觉更好.可惜第三方库稀少是硬伤. 当时我的思路是这样的,用python和selenium来操作浏览器

python 调用shell命令三种方法

#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里. python调用shell命令的方法有许多 1.1   os.system(command) 在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态.这实际上是使用C标准库函数system()实现的.这个函数在执行comman

python调用shell命令

1.1   os.system(command) 在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态.这实际上是使用C标准库函数system()实现的.这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果. 1.2   os.popen(command,mode) 打开一个与command进程之间的管道.这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是'r').如果mode为'r',可以

Python调用外部系统命令

利用Python调用外部系统命令的方法可以提高编码效率.调用外部系统命令完成后可以通过获取命令执行返回结果码.执行的输出结果进行进一步的处理.本文主要描述Python常见的调用外部系统命令的方法,包括os.system().os.popen().subprocess.Popen()等. 1.subprocess模块 优先介绍subprocess模块的是由于该模块可以替代旧模块的方法,如os.system().os.popen()等,推荐使用.subporcess模块可以调用外部系统命令来创建新子

Perl调用外部命令的方式和区别

主要的方式简述如下:1. system("command");使用该命令将开启一个子进程执行引号中的命令,父进程将等待子进程结束并继续执行下面的代码. 2. exec("command");效果同system命令类似,区别是不会开启子进程,而是取代父进程,因此执行完引号中的命令后进程即结束.一般和fork配合使用. 3. `command`;使用反引号调用外部命令能够捕获其标准输出,并按行返回且每行结束处附带一个回车.反引号中的变量在编译时会被内插为其值. 4. o

Python调用7zip命令实现解压

Python调用7zip命令实现文件批量解压 1.输入压缩文件所在的路径 2.可以在代码中修改解压到的文件路径和所需要解压的类型,列入,解压文件夹下面所有的mp4格式的文件 3.cmd 指的就是Python调用dos命令 ,紧跟着的x -r这些全是参考7zip使用书册,及抽取文件夹下所有的以mp4结尾的文件,把文件放入e盘,测试解压文件夹下的new文件夹 # 调用7z命令批量解压文件 import os folder_name = input("请输入文件夹:") os.chdir(f

Perl调用外部命令(其他脚本、系统命令)的方法和区别

1. `command`; 使用反引号调用外部命令能够捕获其标准输出,并按行返回且每行结束处附带一个回车.反引号中的变量在编译时会被内插为其值. 2. open LIST "ls -l|";    open MORE "|more";    @list=<LIST>;    print MORE @list;    close(LIST);    close(MORE);使用带管道的文件句柄来执行外部命令,使用方式与读写文件类似.可以从外部命令的输出读取

python 调用shell命令的方法

在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有执行内容,会在标准输出显示.这实际上是使用C标准库函数system()实现的. 缺点:这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果. 实例:os.system('ls -l *') 2. os.popen(command,