Python OS.popen 错误

0 投票
2 回答
3341 浏览
提问于 2025-04-17 08:03

我正在尝试通过在os.popen中执行这个命令来获取一些文件名:

ls /etc/tor/statistiekjes/ |egrep dns

但是当我运行我的脚本时,我得到了:

<open file 'ls /etc/tor/statistiekjes/ |egrep dns', mode 'r' at 0xb7786860>
egrep: write error: Broken pipe

代码:

lscmd = "ls /etc/tor/statistiekjes/ |egrep "+FILE
print lscmd
inputList=os.popen(lscmd,'r')

文件是传递给脚本的一个参数,用来进行grep操作的。

2 个回答

2

你可以使用subprocess.Popen这个方法,并且加上shell=True的选项:

from subprocess import Popen, PIPE
lscmd = "ls /etc/tor/statistiekjes/ |egrep "+FILE
inputList = Popen(lscmd, shell=True, stdout=PIPE).communicate()[0]
print inputList

祝你好运。

3

对于这个特定的问题,你可以使用原生的Python调用:

import os
import re
for name in (name for name in  os.listdir('/etc/tor/statistiekjes/')
             if re.search(FILE,name)):
    print(repr(name))

不过,你可能想要一个更通用的方法来调用外部程序。在这种情况下,建议使用 subprocess,而不是 os.popen,因为 os.popen 已经不推荐使用了:

import subprocess
import shlex
proc1 = subprocess.Popen(shlex.split('ls /etc/tor/statistiekjes/'),
                         stdout=subprocess.PIPE)
proc2 = subprocess.Popen(shlex.split('egrep {pat}'.format(pat=FILE)),
                         stdin=proc1.stdout,
                         stdout=subprocess.PIPE,stderr=subprocess.PIPE)

proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out,err=proc2.communicate()
print(out)

可以查看 “替代shell管道”

另外, subprocess.Popen 有一个 shell=True 的参数也可以使用。不过,最好尽量避免使用 shell=True,因为这可能会带来安全风险。详细信息可以查看 这里

撰写回答