Tap*_*Dey 10 python subprocess cp
我试图使用子进程调用来执行复制操作(下面的代码):
import subprocess
pr1 = subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = True)
Run Code Online (Sandbox Code Playgroud)
我得到一个错误说:
cp: missing file operand
Try `cp --help' for more information.
Run Code Online (Sandbox Code Playgroud)
当我尝试时shell=False,我明白了
cp: cannot stat `./testdir1/*': No such file or directory
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
我正在使用RedHat Linux GNOME Deskop版本2.16.0以及bash shell和Python 2.6
PS我读了在Python中用Popen发出cp命令的问题中发布的问题,它建议使用shell = True选项,这对我来说并不像我提到的那样:(
unu*_*tbu 17
使用时shell=True,将字符串而不是列表传递给subprocess.call:
subprocess.call('cp -r ./testdir1/* ./testdir2/', shell=True)
Run Code Online (Sandbox Code Playgroud)
文档说:
在Unix上,shell = True,shell默认为/ bin/sh.如果args是一个字符串,则该字符串指定要通过shell执行的命令.这意味着字符串的格式必须与在shell提示符下键入时完全相同.这包括,例如,引用或反斜杠转义带有空格的文件名.如果args是一个序列,则第一个项指定命令字符串,并且任何其他项将被视为shell本身的附加参数.
因此(在Unix上),当列表传递给subprocess.Popen(或subprocess.call)时,列表的第一个元素被解释为命令,列表中的所有其他元素都被解释为shell的参数.因为在您的情况下,您不需要将参数传递给shell,您只需传递一个字符串作为第一个参数.
现在这是一个旧线程,但我只是遇到了同样的问题。
您在此调用中遇到的问题:
subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = False)
Run Code Online (Sandbox Code Playgroud)
是引用了第一个参数之后的每个参数。所以到shell看到的命令是这样的:
cp '-r' './testdir1/*' './testdir2/'
Run Code Online (Sandbox Code Playgroud)
问题在于通配符 ( *)。文件系统在目录中查找字面名称为 ' *' 的testdir1文件,当然,该文件不存在。
解决方案是使用shell = True选项和不引用任何参数来像选择的答案一样拨打电话。