python subprocess.Popen与shlex的对比问题

0 投票
2 回答
1795 浏览
提问于 2025-04-17 02:58

我写的这个子进程命令,首先只搜索我指定的一个目录(s2),而忽略了第一个目录(s1)。其次,我在看Python文档的时候有点困惑。

这是我的代码:

def search_entry(self, widget):
            s1 = subprocess.Popen(['find', '/home/bludiescript/tv-shows', '-type', 'f'], shell=False, stdout=subprocess.PIPE)
            s2 = subprocess.Popen(['find', '/media/FreeAgent\ GoFlex\ Drive/tobins-media', '-type', 'f'],  stdin=s1.stdout, shell=False, stdout=subprocess.PIPE)
            s1.stdout.close()
            self.contents = "\n".join(self.list)
            s2.communicate(self.contents)

我困惑的地方是关于shlex模块的使用,我想知道它能不能替代我代码中的subprocess.Popen,以及这样做是否合理。

所以,像这样的代码会比我现在的代码更好吗?

cmd = 'find /media/FreeAgent\ GoFlex\ Drive/tobins-media -type f find /home/bludiescript/tv-shows -type f'
 spl = shlex.split(cmd)
 s1 = subprocess.Popen(spl, stdout=subprocess.PIPE)
 self.contents = "\n".join(self.list)
        s1.communicate(self.contents)

再次感谢你的建议!

2 个回答

0

试试用os.walk,而不是直接用find。这样写出来的代码会更稳健。下面的代码和你第一次用find的效果是一样的:

top = '/media/FreeAgent GoFlex Drive/tobins-media'
for dirpath, dirnames, filenames in os.walk(top):
    for filename in filenames:
        print os.path.join(dirpath, filename)

不过,这并没有直接回答问题。

2

听起来你想要运行一对命令,并把它们的输出结果合在一起:

cmds = [
    'find /media/FreeAgent\ GoFlex\ Drive/tobins-media -type f',
    'find /home/bludiescript/tv-shows -type f'
]

ouput = '\n'.join(subprocess.check_output(shlex.split(cmd)) for cmd in cmds)

撰写回答