Jon
Jon

Reputation: 1489

Calling 'mv' from Python Popen with wildcard

I can't seem to get the 'mv' command to work from Python subprocess.Popen with a wildcard.

The code:

def moveFilesByType(source, destination, extension):
    params = [] 
    params.append("mv")
    params.append(source + "/*." + extension)       
    params.append(destination + "/") 

    print params

    pipe = subprocess.Popen(params, shell=True, stdout=PIPE)
    result, err = pipe.communicate()

    return result

The output from print params:

    ['mv', '/full_path_to_folder_source/*.nib', '/full_path_to_folder_target/']

The paths here are shortened just for readability, but I assure that they are valid. Calling this exact same command from a terminal works but calling in python gives the standard message about improper use of mv:

usage: mv [-f | -i | -n] [-v] source target
       mv [-f | -i | -n] [-v] source ... directory

I read that in order for wildcards to work, I would need the parameter shell=True in the Popen call, which is present. Any ideas why this doesn't work? Removing shell=True ends up treating the asterisks as hard literals as expected.

Upvotes: 3

Views: 3910

Answers (3)

Staven
Staven

Reputation: 3165

You can do it without starting a new process using modules shutil and glob:

import glob
import shutil

def moveFilesByType(source, destination, extension):
    for path in glob.glob(source + "/*." + extension):
        shutil.move(path, destination)

Upvotes: 3

synthesizerpatel
synthesizerpatel

Reputation: 28056

You shouldn't need to use subprocess for this, check out shutil.copytree

Upvotes: 1

Foo Bah
Foo Bah

Reputation: 26281

Use a string instead of an array:

params = "mv /full_path_to_folder_source/*.nib /full_path_to_folder_target/"

When you specify arguments via the array form, the argument '/full_path_to_folder_source/*.nib' is passed to mv. You want to force bash to expand the argument, but Popen won't pass each argument through the shell.

Upvotes: 9

Related Questions