标签:print rsh stdout over command erro blog sleep shel
import os
statusCode=os.system("powershell sleep 3 ;echo 天下大势为我所控")
print("over",statusCode)
这种方法已经不鼓励使用了
import os
pipe=os.popen("powershell sleep 3 ;echo 天下大势为我所控")
s=pipe.read()
print(s)
这种方法直接接受运行的输出结果,这种方法的缺点是无法获取程序的结束状态。
你道好玩不好玩,os.system()只获取状态不获取输出,os.popen()只获取输出不获取状态,它们各有用武之地。
但是,肯定有一种方法能够同时获取这两者。
这个模块在Python3中已经废弃了
import commands
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status,output
subprocess模块主要有四个方法:
import subprocess
statusCode=subprocess.call("echo one",shell=True)#相当于system命令,只返回状态值,并打印输出到stdout
print(statusCode)
x=subprocess.check_call(["echo"," two"],shell=True)
print(x)
x=subprocess.check_output("echo three",shell=True)#只获取output
print(x)
import subprocess
obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',) #在cwd目录下执行命令
import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close()
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
print(cmd_out)
print(cmd_error)
import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
out_error_list = obj.communicate()
print(out_error_list)
import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out_error_list = obj.communicate('print("hello")')
print(out_error_list)
标签:print rsh stdout over command erro blog sleep shel
原文地址:http://www.cnblogs.com/weidiao/p/7891925.html