subprocess模块
subprocess是一个非常有意思的程序支持,它可以采用管道的形式去启动操作系统的另外一个进程,并且还可以获取此进程的相关信息,subprocess是一个单独的模块,这个模块直接进行call()函数调用即可。
执行命令
1 2 3 4 5 6
| import subprocess def main(): subprocess.call("dir /a", shell=True) if __name__ == "__main__": main()
|

“”” 乱码问题忽略,,pycharm显示换回GBK显示即可,win命令行是GBK显示正确 “””
Popen类
模块里面提供有一个Popen类,同时在该类中给出了如下构造方法
1 2 3 4 5 6 7
| def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None, text=None):
|
这里面最为重要的几个参数是:
- args: 要执行的shell命令,或者是命令的列表
- bufsize: 缓冲区大小
- stdin、stdout、stderr: 表示程序的标准输入、标准输出以及错误输出
- shell: 是否直接执行命令,如果设置为True就表示可以直接执行;
- cwd: 当前的工作目录
- env: 子进程环境变量
创建目录
1 2 3 4 5 6
| import subprocess, time def main(): subprocess.Popen("md www.66xk.wang", shell=True, cwd="e:") if __name__ == "__main__": main()
|

开启进程
既然可以调用命令,那么也可以实现一个子进程的打开与关闭的处理控制,例如,现在要想打开“notepad.exe”程序,并且在其运行3秒之后将该进程关闭。
1 2 3 4 5 6 7 8 9 10 11
| import subprocess, time def main(): notepad_process = subprocess.Popen("notepad.exe", shell=True) time.sleep(3) notepad_process.kill() kill_command = "taskkill /IM notepad.exe" subprocess.Popen(kill_command, shell=True) if __name__ == "__main__": main()
|

标准输入输出相关
subprocess模块里面还有一项功能比较强大的支持在于可以直接使用标准输入、标准输出和错误输出进行进程的数据通讯操作,例如,在Python安装完成之后都会存在有交互式的编程环境,那么本次将通过程序调用交互式编程环境。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import subprocess, time def main(): open_process = subprocess.Popen("python.exe", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE) open_process.stdin.write("print('易金经:www.66xk.wang')\n".encode()) open_process.stdin.write("name = 'sage(智者非智)'\n".encode()) open_process.stdin.write("print('谦谦学者一个:%s' % name)\n".encode()) open_process.stdin.write("print(10+20)\n".encode()) open_process.stdin.write("'No.' + 1\n".encode()) open_process.stdin.close() cmd_out = open_process.stdout.read() open_process.stdout.close() print(cmd_out.decode()) cmd_error = open_process.stderr.read() open_process.stderr.close() print(cmd_error.decode()) if __name__ == "__main__": main()
|
易金经:www.66xk.wang
谦谦学者一个:sage(智者非智)
30
Traceback (most recent call last):
File ““, line 5, in
TypeError: can only concatenate str (not “int”) to str
进程已结束,退出代码0