如何使用子进程使用通配符 (*) 对所有文件进行 tar [英] How to tar all files with wildcard character (*) using subprocess

查看:46
本文介绍了如何使用子进程使用通配符 (*) 对所有文件进行 tar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想在python下运行的命令.基本上我想 tar 文件夹下的所有文件:

This is the command I want to run under python. Basically I want to tar all files under a folder:

tar -jcvf doo.tar.gz /home/user/doo/*

<小时>

import subprocess

subprocess.run(['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

<小时>

后来我用 glob 试了一下.

import subprocess,  glob
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', glob.glob("*")])

返回以下错误:

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

<小时>

以下方法有效,但我不确定如何一个接一个地提供所有文件名:


Following approach works but I am not sure how to provide all file names as one after another:

import subprocess,  glob
subprocess.run(['tar', '-jcvf', 'doo.tar.gz', 'hello.txt', 'world.txt'])

推荐答案

subprocess.run(['tar', '-jcvf', 'doo.tar.gz', glob.glob("*")])

glob 返回一个字符串列表.你不应该把它嵌入到传递给 run 的列表中,而是附加它.

glob returns a list of strings. You shouldn't embed that inside the list passed to run, but instead append it.

subprocess.run(['tar', '-jcvf', 'doo.tar.gz'] + glob.glob("*"))

请注意,您已省略主目录.

Note that you've ommitted the home directory.

subprocess.run(['tar', '-jcvf', 'doo.tar.gz'] + glob.glob("/home/user/doo/*"))

这篇关于如何使用子进程使用通配符 (*) 对所有文件进行 tar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆