subprocess中的Popen用法

subprocess模块

  • Popen基本格式: subprocess.Popen('命令',shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    shell=True 表示在终端中运行的命令,stdout=subprocess.PIPE 表示当命令存在的时候把结果写入stdout管道,
    stderr=subprocess.PIPE 表示的是当命令不存在的时候把结果写入stderr管道

  • subprocess是python内置的模块,这个模块中的Popen可以查看用户输入的命令行是否存在
  • 如果命令存在,把内容写入stdout管道
  • 如果命令不存在,则把信息写入stderr管道

    需要注意的是这个模块的返回结果只能让开发者查看一次,再次查看就无效了,为了能够重复使用,必须在第一次查看的时候
    就把所有的信息保存到变量中。

import subprocess
r = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# subprocess是python内置的模块,这个模块中的Popen可以查看用户输入的命令行是否存在
print(r.stdout.read().decode('utf-8'))
print(r.stderr.read().decode('utf-8'))
# 输出结果:未命名.ipynb  client.py  server.py

猜你喜欢

转载自www.cnblogs.com/ddzc/p/12382534.html
今日推荐