How to use mv command in Python with subprocess

I have many files in / home / somedir / subdir / and I'm trying to move them all to / home / somedir programmatically.

right now i have this:

subprocess.call(["mv", "/home/somedir/subdir/*", "somedir/"]) 

but this gives me this error:

 mv: cannot stat `/home/somedir/subdir/*': No such file or directory 

I know that it exists, because when I type the mv command manually using the same command as the script, it works fine.

+7
python unix subprocess mv stat
source share
3 answers

if you call the subprocess this way:

 subprocess.call(["mv", "/home/somedir/subdir/*", "somedir/"]) 

you are actually passing the argument /home/somedir/subdir/* to the mv command with the actual * file. those. You are trying to move the file * .

 subprocess.call("mv /home/somedir/subdir/* somedir/", shell=True) 

he will use a shell that will extend the first argument.

Nota Bene: when using the shell=True argument, you need to change the argument list into a string to be passed to the shell.

Hint: you can also use the os.rename() or shutil.move() functions together with os.path.walk() or os.listdir() to move files to the destination in a more pythonic way.

+10
source share

You can solve this problem by adding the shell=True parameter to take into account the wildcards in your case (and therefore write the command directly, without any list):

 subprocess.call("mv /home/somedir/subdir/* somedir/", shell=True) 

Without this, the argument is passed directly to the mv command with an asterisk. It is the task of the shell to return all files that match the template as a whole.

+2
source share

You use shell globbing * and expect the mv command to know what that means. You can get the same error from the shell as follows:

$ mv 'somedir/subdir/*' ...

Pay attention to the quotation marks. The shell usually does global matching on * for you, but commands do not do this on their command lines; not even a shell. There is a C library function called fnmatch that makes for you a shader style style that every programming language more or less copies. In Python, it can be the same name. Or it might have the word globe; I do not remember.

+2
source share

All Articles