[英]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.