Python 如何使用子流程对所有带有通配符(*)的文件进行tar
这是我想在python下运行的命令。基本上,我希望Python 如何使用子流程对所有带有通配符(*)的文件进行tar,python,subprocess,wildcard,Python,Subprocess,Wildcard,这是我想在python下运行的命令。基本上,我希望tar文件夹下的所有文件: tar -jcvf doo.tar.gz /home/user/doo/* 返回以下错误: tar: Removing leading `/' from member names tar: /home/user/doo/*: Cannot stat: No such file or directory tar: Exiting with failure status due to previous errors
tar
文件夹下的所有文件:
tar -jcvf doo.tar.gz /home/user/doo/*
返回以下错误:
tar: Removing leading `/' from member names
tar: /home/user/doo/*: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
Traceback (most recent call last):
File "dd.py", line 4, in <module>
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', glob.glob("*")])
File "/usr/local/lib/python3.5/subprocess.py", line 693, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/local/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/local/lib/python3.5/subprocess.py", line 1490, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert 'list' object to str implicitly
后来我用
glob
试了一下
import subprocess, glob
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', glob.glob("*")])
返回以下错误:
tar: Removing leading `/' from member names
tar: /home/user/doo/*: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
Traceback (most recent call last):
File "dd.py", line 4, in <module>
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', glob.glob("*")])
File "/usr/local/lib/python3.5/subprocess.py", line 693, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/local/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/local/lib/python3.5/subprocess.py", line 1490, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert 'list' object to str implicitly
glob
返回字符串列表。您不应该将其嵌入传递给run
的列表中,而是将其追加
subprocess.run(['tar', '-jcvf', 'doo.tar.gz'] + glob.glob("*"))
请注意,您已经输入了主目录
subprocess.run(['tar', '-jcvf', 'doo.tar.gz'] + glob.glob("/home/user/doo/*"))
Shell是可以扩展的。因此,在子流程调用中指定
shell=True
,以将其展开
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', '/home/user/doo/*'], shell=True)
我也可以这样做:
res=subprocess.check_output(['tar','-jcvf','doo.tar.gz']+glob.glob(“*”))。decode('utf-8')
以获得输出吗@约翰·库格曼
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', '/home/user/doo/*'], shell=True)