簡體   English   中英

使用子進程模塊在Python中執行管道命令的任何方法,而不使用shell = True?

[英]Any way to execute a piped command in Python using subprocess module, without using shell=True?

我想從Python運行一個管道命令行linux / bash命令,它首先記錄文件,然后拆分tar文件。 命令在bash中看起來像這樣:

> tar -cvf - path_to_archive/* | split -b 20m -d -a 5 - "archive.tar.split"

我知道我可以使用子進程執行它,通過設置shell = True,並將整個命令作為字符串提交,如下所示:

import subprocess    

subprocess.call("tar -cvf - path_to_archive/* | split -b 20m -d -a 5 - 'archive.tar.split'", shell=True)

...但出於安全原因,我想找到一種方法來跳過“shell = True”部分(它采用字符串列表而不是完整的命令行字符串,並且無法正確處理管道char)。 在Python中有沒有解決方案? 即,是否有可能以某種方式設置鏈接管道,或其他一些解決方案?

如果要避免使用shell = True,可以手動使用子進程管道

from subprocess import Popen, PIPE
p1 = Popen(["tar", "-cvf", "-", "path_to_archive"], stdout=PIPE)
p2 = Popen(["split", "-b", "20m", "-d", "-a", "5", "-", "'archive.tar.split'"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

請注意,如果不使用shell,則無法訪問*等泛化字符的擴展。 相反,您可以使用glob模塊。

tar可以分裂:

tar -L 1000000 -F name-script.sh cf split.tar largefile1 largefile2 ...

name-script.sh

#!/bin/bash
echo "${TAR_ARCHIVE/_part*.tar/}"_part"${TAR_VOLUME}".tar >&"${TAR_FD}"

要重新組裝

tar -M -F name-script.sh cf split.tar

將它添加到您的python程序中。

你有什么理由不能使用tarfile嗎? | http://docs.python.org/library/tarfile.html

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

使用tarfile編寫類似於對象的文件而不是調用子進程。

無恥的插件,我寫了一個子進程包裝器,以便在python中更容易命令管道: https//github.com/houqp/shell.py

例:

shell.ex("tar -cvf - path_to_archive") | "split -b 20m -d -a 5 - 'archive.tar.split'"

暫無
暫無

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

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