簡體   English   中英

在subprocess.Popen中使用&&進行命令鏈接?

[英]Using && in subprocess.Popen for command chaining?

我使用subprocess.PopenPython ,我還沒有碰到過加盟命令(即foob​​ar的一個優雅的解決&&通過bizbang) 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菊花鏈接多個命令。


我想在盡可能少的命令塊中復制此輸出。

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)

這個怎么樣:

from subprocess import Popen, PIPE

def log_command_outputs(commands):
    processes = [Popen(cmd, stdout=PIPE) for cmd in commands]
    outputs = [proc.communicate()[0].split() for proc in processes]
    for output in outputs:
        for line in output:
            script_log.write(line)
        script_long.write("\n")

這會並行啟動命令,這可能會比逐個執行命令(但可能不是很大)。 由於communicate調用是順序的,因此任何具有大輸出(超過管道緩沖區)的命令都將阻塞,直到它被清理為止。

對於您的示例命令鏈,您將調用:

log_command_outputs([["mmls", "WinXP.E01"], ["stat", "WinXP.E01"]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM