wangluo010 发表于 2018-8-11 12:53:14

Python 调用系统命令

  os.system
  os.spawn
  os.popen
  popen2
  commands
  这些东西统统将被subprocess取代,subprocess真的很好用,有没有!
  1、subprocess.call()
  subprocess.call()参数是一个列表,如果想把shell命令以字符串的形式传进来,需要添加shell=True这个参数。
>>> from subprocess import call  
>>> call("df -h",shell=True)
  
Filesystem      SizeUsed Avail Use% Mounted on
  
/dev/disk1      112G   75G   38G67% /
  0
  如果不指定shell=True,需要传递一个列表作为参数
>>> call(['df','-h'])  
Filesystem      SizeUsed Avail Use% Mounted on
  
/dev/disk1      112G   75G   38G67% /
  0
  返回值是shell的returncode
  2、subprocess.Popen()
  call方法是Popen的一个封装,call 的返回值是shell的退出码,Popen返回的是一个Popen对象。使用起来比较方便,但是是阻塞的,会一直等到call方法执行完,才能继续执行。Popen是非阻塞的,相当于放到后台执行,如果需要拿到shell命令的标准输出,错误输出的时候,用Popen比较方便。
>>> from subprocess import Popen,PIPE  
>>> pobj = Popen('ls -l',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  
>>> result = pobj.communicate()
  此时result以一个列表的方式返回,result为标准输出,result是错误输出
>>> exitcode = pobj.poll()  
>>> print exitcode
  2
  调用Popen对象的poll方法,返回shell退出码
  下面是封装的一个方法,参数是要传递的命令,如果不添加shell=True,需要以列表的方式传递命令,否则,传一个字符串。函数返回一个列表,分别是标准输出,错误输出和returncode
from subprocess import Popen,PIPEdef execcommand(commandstr):  
    process = Popen(commandstr,stdout=PIPE,stderr=PIPE,shell=True)
  
    res = process.communicate()
  
    toout = res
  
    toerr = res
  
    exitcode = process.poll()
  
    result =
  
    return result
页: [1]
查看完整版本: Python 调用系统命令