使用&&在subprocess.Popen中进行命令链接? [英] Using && in subprocess.Popen for command chaining?

查看:146
本文介绍了使用&&在subprocess.Popen中进行命令链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将subprocess.PopenPython结合使用,并且还没有遇到一种通过Popen连接命令(即foobar && bizbang)的优雅解决方案.

I'm using subprocess.Popen with Python, and I haven't come across an elegant solution for joining commands (i.e. foobar&& bizbang) via Popen.

我可以这样做:

p1 = subprocess.Popen(["mmls", "WinXP.E01"], stdout=subprocess.PIPE)
result = p1.communicate()[0].split("\n")
for line in result:
    script_log.write(line)

script_log.write("\n")

p1 = subprocess.Popen(["stat", "WinXP.E01"], stdout=subprocess.PIPE)
result = p1.communicate()[0].split("\n")
for line in result:
    script_log.write(line)


但这在美学上确实并不令人满意(尤其是当我通过Popen菊花链式链接多个命令时.)


But that really isn't very aesthetically pleasing (especially if I'm daisy-chaining multiple commands via Popen.

我想在尽可能少的命令块中复制此输出.

not@work ~/ESI/lab3/images $ mmls WinXP.E01 && echo -e "\n" && stat WinXP.E01
DOS Partition Table
Offset Sector: 0
Units are in 512-byte sectors

     Slot    Start        End          Length       Description
00:  Meta    0000000000   0000000000   0000000001   Primary Table (#0)
01:  -----   0000000000   0000000062   0000000063   Unallocated
02:  00:00   0000000063   0020948759   0020948697   NTFS (0x07)
03:  -----   0020948760   0020971519   0000022760   Unallocated


  File: `WinXP.E01'
  Size: 4665518381  Blocks: 9112368    IO Block: 4096   regular file
Device: 14h/20d Inode: 4195953     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/    nott)   Gid: ( 1000/    nott)
Access: 2013-03-16 23:20:41.901326579 -0400
Modify: 2013-03-04 10:05:50.000000000 -0500
Change: 2013-03-13 00:25:33.254684050 -0400
 Birth: -


有什么建议吗?

注意:我想避免在subprocess.Popen


Any suggestions?

Note: I'd like to avoid typing this into subprocess.Popen

p1 = subprocess.Popen(["mmls WinXP.E01 && echo -e '\n' && stat WinXP.E01"], stdout=subprocess.PIPE)

推荐答案

&&是shell运算符,POpen默认情况下不使用shell.

&& is a shell operator, POpen does not use a shell by default.

如果要使用外壳程序功能,请在POpen调用中使用shell = True,但请注意,它稍微慢一些/占用更多内存.

If you want to use shell functionality use shell=True in your POpen call, but be aware that it is slightly slower/more memory intensive.

p1 = subprocess.Popen(["mmls", "WinXP.E01", "&&", "echo", "-e", "\"\n\"", "&&", "stat", "WinXP.E01"],
                      stdout=subprocess.PIPE, shell=True)

这篇关于使用&&在subprocess.Popen中进行命令链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆