标签:erro 进程 dex pad open 标准输入 多个 文本文件 系统默认
subprocess最早在2.4版本引入。用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值。
1
2
3
4
5
6
7
|
# subprocess用来替换多个旧模块和函数 os.system os.spawn * os.popen * popen2. * commands. * |
运行python的时候,我们都是在创建并运行一个进程,linux中一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在python中,我们通过标准库中的subprocess包来fork一个子进程,并且运行一个外部的程序。subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所欲我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。
1. call
执行命令,返回状态码,shell = True允许shell命令时字符串形式
1
2
|
subprocess.check_call([ "ls" , "-l" ]) subprocess.check_call( "exit 1" , shell = True ) |
2. check_call
执行命令,如果执行状态码是0,则返回0,否则抛出异常
1
2
|
subprocess.check_call([ "ls" , "-l" ]) subprocess.check_call( "exit 1" , shell = True ) |
3. check_output
执行命令,如果状态码是0,则返回执行结果,否则抛出异常
1
2
|
subprocess.check_output([ "echo" , "Hello World!" ]) subprocess.check_output( "exit 1" , shell = True ) |
4. subprocess.Popen(...)
用于执行复杂的系统命令
参数:
执行普通命令:
1
2
3
|
import subprocess ret1 = subprocess.Popen([ "mkdir" , "t1" ]) ret2 = subprocess.Popen( "mkdir t2" , shell = True ) |
终端输入的命令分为两种:
1
2
3
|
import subprocess obj = subprocess.Popen( "mkdir t3" , shell = True , cwd = ‘/home/dev‘ ,) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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) |
1
2
3
4
5
6
7
8
|
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) |
1
2
3
4
5
|
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) |
标签:erro 进程 dex pad open 标准输入 多个 文本文件 系统默认
原文地址:http://www.cnblogs.com/sweet521/p/7324884.html