簡體   English   中英

為什么 tar 在使用 * 通配符時通過 Python 的 subprocess.call 調用時無法創建存檔?

[英]Why does tar fail to create an archive when called via Python's subprocess.call while using a * wildcard?

我正在編寫一個 python 腳本,它應該從現有文件中提取一些數據,然后將原始文件打包成幾個 tarball。 文件名格式如下所示:

system_yymmddT0000.zip

其中system可以是多個名稱之一, YYMMDDThhmm是創建日期和時間。

為了使這項工作,我使用焦油通過Python的subprocess.call所以,對於開始日期1704文件一樣SAP_1704T0000.zip ,命令是:

subprocess.call(["tar", "-cvf", "SAP_2017_04.tar", "SAP_1704*", "1>", "SAP_2017_04.filelist"])

但是,當我運行此腳本時,出現以下錯誤:

tar: SAP_1704*: Cannot stat: No such file or directory
tar: 1>: Cannot stat: No such file or directory
tar: SAP_2017_04.filelist: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

我還嘗試將所有參數打包在一起,如下所示:

subprocess.call(["tar", "-cvf SAP_2017_04.tar SAP_1704* 1> SAP_2017_04.filelist"]) (參數之間沒有逗號)。 但是,然后我收到以下錯誤:

tar: Cowardly refusing to create an empty archive
Try `tar --help' or `tar --usage' for more information.

我不知道我做錯了什么,因為在文件夾內手動導航並運行命令tar cvf SAP_2017_04.tar SAP_1704* 1> SAP_2017_04.filelist工作得很好。

通配符不由tar處理,它們需要由調用它的程序處理。 通常,該程序是一個外殼程序。

然而,它不一定是; 通過在本機 Python 中完成工作而不是使用shell=True ,您可以獲得更安全的操作(如果您的任何參數是用戶可配置的):

subprocess.call(['tar', '-cvf', 'SAP_2017_04.tar'] + glob.glob('SAP_1704*'),
                stdout=open('SAP_2017_04.filelist', 'w'))
  • 取而代之的1>somefile你的shell中的重定向標准輸出,FD 1,指令寫入somefile ),我們使用stdout=open('somefile', 'w')來告訴Python同樣的事情。
  • 我們不是直接將SAP_1704*放在命令行中,而是在 Python 中調用glob.glob('SAP_1704*') ,並將它返回的列表添加到參數列表中。

沒關系,自己想出來的(至少我是這么認為的)。 它是這樣工作的:

substring = r"tar, -cvf SAP_2017_04.tar SAP_1704* 1> SAP_2017_04.filelist"
subprocess.call(substring, shell=True)

似乎有兩個問題 - 轉義一些特殊字符並嘗試將參數列表傳遞給subprocess.call而在使用shell=True時它應該作為單個字符串傳遞。

非常感謝@CMMCD @BoarGules 和@ErHarshRathore 讓我走上正軌!

暫無
暫無

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

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