如何在带有子进程的 Python 中使用 mv 命令 [英] How to use the mv command in Python with subprocess
问题描述
我在/home/somedir/subdir/中有很多文件,我正在尝试以编程方式将它们全部移动到/home/somedir.
I have a lot of files in /home/somedir/subdir/ and I'm trying to move them all up to /home/somedir programmatically.
现在我有这个:
subprocess.call(["mv", "/home/somedir/subdir/*", "somedir/"])
但它给了我这个错误:
mv: cannot stat `/home/somedir/subdir/*': No such file or directory
我知道它确实存在,因为当我使用与脚本使用完全相同的命令手动键入 mv 命令时,它可以完美运行.
I know that it does exist because when I type the mv command by hand using the exact same command as the script uses it works perfectly.
推荐答案
如果你这样调用子进程:
if you call subprocess that way:
subprocess.call(["mv", "/home/somedir/subdir/*", "somedir/"])
您实际上将参数 /home/somedir/subdir/*
提供给 mv
命令,并带有实际的 *
文件.即您实际上是在尝试移动 *
文件.
you're actually giving the argument /home/somedir/subdir/*
to the mv
command, with an actual *
file. i.e. you're actually trying to move the *
file.
subprocess.call("mv /home/somedir/subdir/* somedir/", shell=True)
它将使用扩展第一个参数的 shell.
it will use the shell that will expand the first argument.
Nota Bene:当使用 shell=True
参数时,您需要将参数列表更改为将提供给 shell 的字符串.
Nota Bene: when using the shell=True
argument you need to change your argument list into a string that will be given to the shell.
提示:您还可以使用 os.rename()
或 shutil.move()
函数,以及 os.path.walk()
或 os.listdir()
以更pythonic的方式将文件移动到目的地.
Hint: You can also use the os.rename()
or shutil.move()
functions, along with os.path.walk()
or os.listdir()
to move the files to destination in a more pythonic way.
这篇关于如何在带有子进程的 Python 中使用 mv 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!