python – 在subprocess.Popen中使用\u0026\u0026进行命令链接?

我正在使用subprocess.Popen和Python,我没有遇到通过Popen加入命令(即foobar&& bizbang)的优雅解决方案.

我能做到这一点:

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菊花链接多个命令.

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

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中键入它

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

解决方法:

&安培;&安培;是一个shell操作符,POpen默认不使用shell.

如果你想使用shell功能在你的POpen调用中使用shell = True,但要注意它稍慢/内存密集.

p1 = subprocess.Popen(["mmls", "WinXP.E01", "&&", "echo", "-e", "\"\n\"", "&&", "stat", "WinXP.E01"],
                      stdout=subprocess.PIPE, shell=True)
上一篇:Go+Python双语言混合开发


下一篇:javascript – 如何通过链接早期附加的方法将事件附加到表单的onSubmit事件?