Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1014448
  • 博文数量: 157
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1388
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-09 15:37
文章分类

全部博文(157)

文章存档

2023年(9)

2022年(2)

2021年(18)

2020年(7)

2017年(13)

2016年(53)

2015年(55)

我的朋友

分类: Python/Ruby

2023-06-19 19:04:56

import subprocess
import os
1.  如果你的应用使用的是Python 3.5及以上的版本:
subprocess.run()
默认参数shell=False,m1和m2等同,m3会报错,默认参数univer

点击(此处)折叠或打开

  1. m1=subprocess.run(['ls','/home/liq_test'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2. m2=subprocess.run(['ls /home/liq_test'],stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
  3. m=subprocess.run(['ls /home/liq_test'],stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True,universal_newlines=True)
  4. print(m1)
  5. CompletedProcess(args=['ls', '/home/liq_test'], returncode=0, stdout=b'hello.txt\nworld.txt\n你好\n', stderr=b'')
  6. print(m)
  7. CompletedProcess(args=['ls /home/liq_test'], returncode=0, stdout='hello.txt\nworld.txt\n你好\n', stderr='')

注意m.stdout.strip()的结果是bytes, 想str类型需要decode(m.stdout.strip(),"utf-8") 得到输出的值,但我看报错了所以还是universal_newlines=True这个吧

2.  如果你的应用使用的Python 2.4以上,但是是Python 3.5以下的版本:

点击(此处)折叠或打开

  1. m=subprocess.call(['ls /home/liq_test'],shell=True,universal_newlines=False)
  2. hello.txt world.txt 你好
  3. print(m)
  4. 0
  5. n=subprocess.check_output(['ls /home/liq_test'],shell=True,universal_newlines=False)
  6. print(n)
  7. b'hello.txt\nworld.txt\n你好\n'

3.  新老使用对比

点击(此处)折叠或打开

  1. m=subprocess.call(['ls','/home/liq_test'])
  2. m=os.system('/home/liq_test')
  3. 0

4.  新老使用对比

点击(此处)折叠或打开

  1. m=subprocess.getoutput('/home/liq_test')
  2. m=os.popen('/home/liq_test').read()
  3. print(m)
  4. 'hello.txt\nworld.txt\n你好\n'

5. 
subprocess.run()、subprocess.call()、subprocess.check_call()和subprocess.check_output()都是通过对subprocess.Popen的封装来实现的高级函数,因此如果我们需要更复杂功能时,可以通过subprocess.Popen来完成。

参考:https://blog.csdn.net/qdPython/article/details/127689439


阅读(156) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~