本篇文章给大家带来的内容是关于
python
中subprocess库的用法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
介绍
使用subprocess模块的目的是用于替换os.system等一些旧的模块和方法。
导入模块
命令执行call()
立即学习
“
Python免费学习笔记(深入)
”;
执行由参数提供的命令,把数组作为参数运行命令。其功能类似于os.system(cmd)。
其中参数shell默认为False。
在shell设置为True时,可以直接传字符串:
获得返回结果check_output()
call()是不返回显示的结果的,可以使用check_ouput()来获得返回的结果:
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
进程创建和管理Popen类
subprocess.popen代替os.popen。可以创建一个Popen类来创建进程和进行复杂的交互。
创建不等待的子进程
添加子进程等待
添加了wait()后,主进程会等待子进程结束再执行下面的语句。
子进程文本流控制
标准输出重定向:
使用stdin与其配合使用:
>>> import subprocess>>> subprocess.call(['ls','-l')>>> subprocess.call('ls -l',shell=True)>>> result = subprocess.check_output(['ls','-l'],shell=True)
>>> result.decode('utf-8')import subprocess
child = subprocess.Popen(['ping','-c','4','www.baidu.com'])
print('Finished')import subprocess
child = subprocess.Popen(['ping','-c','4','www.baidu.com'])
child.wait() # 等待子进程结束
print('Finished')import subprocess
child = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE) #将标准输出定向输出到subprocess.PIPE
print(child.stdout.read())import subprocess
child1 = subprocess.Popen(['cat','/etc/passwd'],stdout=subprocess.PIPE)
child2 = subprocess.Popen(['grep','root'],stdin=child1.stdout,stdout=subprocess.PIPE)
print child2.communicate()