Python 捕获命令发送到 unix,捕获输出并写入文件
Python capture command send to unix, capture output and write to file
import subprocess
cmd = 'ifconfig -a'
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
<<<HOW TO CMD SENT AND IT'S OUTPUT>>>
file = open('outputFile.txt', 'w+')
file.write(out)
file.close()
from subprocess import Popen, PIPE, STDOUT
cmd = ["ifconfig", "-a"]
p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
stdout, stderr = p.communicate()
print stdout
捕获输出并写入文件:python ifconfig.py > outputfile.txt
import subprocess
cmd = 'ifconfig -a'
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
<<<HOW TO CMD SENT AND IT'S OUTPUT>>>
file = open('outputFile.txt', 'w+')
file.write(out)
file.close()
from subprocess import Popen, PIPE, STDOUT
cmd = ["ifconfig", "-a"]
p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
stdout, stderr = p.communicate()
print stdout
捕获输出并写入文件:python ifconfig.py > outputfile.txt