标签:
1、call
执行命令,返回状态码
ret = subprocess.call([‘ls‘, ‘-l‘], shell=False) ret = subprocess.call(‘ls -l‘, shell=True)
2、check_call
执行命令,如果执行状态码是0,则返回0,否则抛异常
subprocess.check_call(["ls", "-l"]) subprocess.check_call("exit 1", shell=True)
3、check_output
执行命令,如果状态是0,则返回执行结果,否则抛异常
subprocess.check_output(["echo", "hello world !"]) subprocess.check_output(["exit 1", shell=True])
用于执行复杂的系统命令
参数:
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin,stdout,stderr)
案例: import subprocess ret1 = subprocess.Popen(["mkdir", "t1"]) ret2 = subprocess.Popen("mkdir t2", shell=True)
输入即可得到输出,如:ifconfig
输入进行某环境,依赖在输入,如:python
import subprocess obj = subprocess.Popen("mkdir t3", shell=True, cwd=‘/home/dev‘)
import subprocess obj = subprocess.Popen(["python"], stdin=dubprocess.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)
标签:
原文地址:http://www.cnblogs.com/renfanzi/p/5644143.html