alper
alper

Reputation: 3410

How to tar all files with wildcard character (*) using subprocess

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/*'])

That returns following error:

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

Later I tried it using glob.

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

That returns following error:

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'])

Upvotes: 1

Views: 1482

Answers (2)

Sunitha
Sunitha

Reputation: 12015

Shell is the one that can expand *. So specify shell=True in your subprocess call to expand it.

subprocess.run(['tar', '-jcvf', 'doo.tar.gz', '/home/user/doo/*'], shell=True)

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361919

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

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/*"))

Upvotes: 2

Related Questions