呼叫“mv”来自带有通配符的 Python Popen
我似乎无法使用通配符从 Python subprocess.Popen
获取“mv”命令。
代码:
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
print params
的输出:
['mv', '/full_path_to_folder_source/*.nib', '/full_path_to_folder_target/']
这里的路径被缩短只是为了便于阅读,但我保证它们是有效的。从终端调用这个完全相同的命令是可行的,但在 python 中调用会给出有关 mv 的不正确使用的标准消息:
usage: mv [-f | -i | -n] [-v] source target
mv [-f | -i | -n] [-v] source ... directory
我读到为了使通配符起作用,我需要参数 shell= Popen
调用中存在 True。有什么想法为什么这行不通吗?删除 shell=True
最终会按照预期将星号视为硬文字。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用字符串而不是数组:
当您通过数组形式指定参数时,参数
'/full_path_to_folder_source/*.nib'
将传递给mv
。您想要强制 bash 展开参数,但Popen
不会通过 shell 传递每个参数。Use a string instead of an array:
When you specify arguments via the array form, the argument
'/full_path_to_folder_source/*.nib'
is passed tomv
. You want to force bash to expand the argument, butPopen
won't pass each argument through the shell.您可以在不启动新进程的情况下使用模块shutil 和 glob 来完成此操作:
You can do it without starting a new process using modules shutil and glob:
您不需要为此使用子进程,请查看 shutil.copytree
You shouldn't need to use subprocess for this, check out shutil.copytree