如何在带有子进程的 Python 中使用 mv 命令 [英] How to use the mv command in Python with subprocess

查看:51
本文介绍了如何在带有子进程的 Python 中使用 mv 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在/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屋!

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