簡體   English   中英

Python - 如何使用 pipe 調用 bash 命令?

[英]Python - How to call bash commands with pipe?

我在Linux的命令行可以正常運行這個:

$ tar c my_dir | md5sum

但是,當我嘗試使用 Python 調用它時,出現錯誤:

>>> subprocess.Popen(['tar','-c','my_dir','|','md5sum'],shell=True)
<subprocess.Popen object at 0x26c0550>
>>> tar: You must specify one of the `-Acdtrux' or `--test-label'  options
Try `tar --help' or `tar --usage' for more information.

你必須使用subprocess.PIPE ,也在拆分命令,你應該使用shlex.split()以防止怪異的行為在某些情況下:

from subprocess import Popen, PIPE
from shlex import split
p1 = Popen(split("tar -c mydir"), stdout=PIPE)
p2 = Popen(split("md5sum"), stdin=p1.stdout)

但是要創建存檔並生成其校驗和,您應該使用Python內置模塊tarfilehashlib而不是調用shell命令。

好吧,我不確定為什么,但這似乎有效:

subprocess.call("tar c my_dir | md5sum",shell=True)

任何人都知道為什么原始代碼不起作用?

您真正想要的是使用shell命令作為參數運行shell子進程:

>>> subprocess.Popen(['sh', '-c', 'echo hi | md5sum'], stdout=subprocess.PIPE).communicate()
('764efa883dda1e11db47671c4a3bbd9e  -\n', None)

我會在 python v 3.8.10上試試你的:

import subprocess
proc1 = subprocess.run(['tar c my_dir'], stdout=subprocess.PIPE, shell=True)
proc2 = subprocess.run(['md5sum'], input=proc1.stdout, stdout=subprocess.PIPE, shell=True)
print(proc2.stdout.decode())

要點(如我在相關https://stackoverflow.com/a/68323133/12361522上的解決方案中的概述):

  • subprocess.run()
  • bash 命令和參數沒有拆分,即['tar c my_dir']["tar c my_dir"]
  • 所有進程的stdout=subprocess.PIPE
  • input=proc1.stdout前一個輸出到下一個輸入的鏈
  • 啟用 shell shell=True
>>> from subprocess import Popen,PIPE
>>> import hashlib
>>> proc = Popen(['tar','-c','/etc/hosts'], stdout=PIPE)
>>> stdout, stderr = proc.communicate()
>>> hashlib.md5(stdout).hexdigest()
'a13061c76e2c9366282412f455460889'
>>> 

暫無
暫無

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

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