【问题标题】:How to use subprocess.Popen() instead of os.popen() in Python?如何在 Python 中使用 subprocess.Popen() 而不是 os.popen()?
【发布时间】:2020-08-05 08:54:24
【问题描述】:

由于不推荐使用 os.popen,我想使用 subprocess.Popen(也因为它在各个方面都更加健壮)。我最初有这个,但不知道如何进行适当的转换。

PID_FILE = 'process.pid'
if os.path.exists( PID_FILE ):
    pid = int(open( PID_FILE,'rb').read().rstrip('\n'))
    pinfo = os.popen('ps %i' % pid).read().split('\n')

任何帮助将不胜感激。

【问题讨论】:

  • 你为什么看不到文档
  • 我看过但老实说无法理解它,因为我仍然是 Python 的初学者并且进展缓慢。

标签: python python-3.x subprocess popen


【解决方案1】:

只需使用subprocess.Popen 创建一个新进程,将其标准输出重定向到 PIPE,以文本模式读取其标准输出。

Python 版本 >= 3.6

from subprocess import Popen, PIPE
with Popen(f'ps {pid}'.split(), stdout=PIPE, text=True) as proc:
    pinfo = proc.stdout.readlines()

正如您对 python2.7 的要求,我已经给出了代码。但请记住,python2.7 已达到 EOL,您应该使用 python3.x

Python 版本 = 2.7

from subprocess import Popen, PIPE
proc = Popen(f'ps {pid}'.split(), stdout=PIPE)
pinfo = proc.stdout.readlines()

更多信息请参考subprocess documentation

【讨论】:

  • 您好,感谢您的回复。试了一下,报错:with Popen(f'ps {pid}'.split(), stdout=PIPE, text=True) as proc: ^ SyntaxError: invalid syntax
  • 看起来您使用的是 python 版本 f'ps {pid}' 更改为'ps %i' % pid',就像您在代码中所做的那样。但我强烈建议您升级到最新版本的 python
  • 知道了。我用的是 2.7 你没看错。当然我会升级它谢谢!
  • 我现在正在使用这个:with Popen(('ps %i' % pid).split(), shell=True, stdout=PIPE) as proc: 并收到此错误 AttributeError: exit 我做错了吗?
  • 但是请记住,python2.7 已经到了 EOL,你应该真的在使用 python3.x
猜你喜欢
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2012-03-25
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多