在平时的任务中,我们往往需要调用外部的程序或者命令,那么Python中怎么调用外部命令和程序呢?今天我们将讨论4种调用方法os.system(),os.popen(), commands模块,subprocess模块。
一。os.system()
system方法会创建子进程执行外部程序。方法仅仅返回外部程序的执行结果。0表示执行成功。
>>> import os
>>> os.system("ls")
>>> os.system("cat more.py|grep python")
>>> os.system("/home/nginx/sbin/nginx -c /home/nginx/conf/nginx.conf")
二。os.popen()
popen方法可以得到shell命令的返回值。os.popen(cmd)后,须要再调用read()或者readlines()这两个命令。输出结果
>>> os.popen("/bin/ls")
>>> os.popen("/bin/ls").read()
>>> os.popen("/bin/ls").readlines()
三。commands模块(python2.*的版本)
>>> import commands
>>> result = commands.getoutput('/bin/ls')
>>> print result
四。subprocess模块
>>> import subprocess
>>> subprocess.call("ls")
>>> subprocess.call(["ls","-l"])
>>> subprocess.Popen("ls")
>>> subprocess.Popen(["ls","-l"])
简单地讲述了4种执行外部命令和程序的方法,进一步的使用建议读者阅读工具书,并结合上机来熟悉。