我试图使用子进程调用来执行复制操作(代码如下):
import subprocess
pr1 = subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = True)
和我有一个错误说:
cp: missing file operand
Try `cp --help' for more information.
当我尝试使用shell=False
时,我得到
cp: cannot stat `./testdir1/*': No such file or directory
我如何解决这个问题?
我正在使用 RedHat Linux GNOME Deskop 版本 2.16.0 和 bash shell 和 Python 2.6
P.S.我读了Problems with issuing cp command with Popen in Python中发布的问题,它建议使用shell = True
选项,正如我提到的那样,这对我不起作用:(
当使用shell=True
时,传递一个字符串,而不是一个列表到subprocess.call
:
subprocess.call('cp -r ./testdir1/* ./testdir2/', shell=True)
The docs say:
在 shell = True 的 Unix 上,shell 默认为 / bin / sh。如果 args 是字符串,则该字符串指定要通过 shell 执行的命令。这意味着字符串的格式必须与在 shell 提示符下键入时的格式完全相同。例如,这包括引用或反斜杠转义文件名,并在其中加上空格。如果 args 是一个序列,则第一项指定命令字符串,并且 shell 参数本身的任何其他项将被视为附加的。
因此(在 Unix 上),当列表传递给subprocess.Popen
(或subprocess.call
)时,列表的第一个元素被解释为命令,列表中的所有其他元素被解释为参数对于shell。
这是一个旧的线程,但我只是有同样的问题。
你有这个电话的问题:
subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = False)
是第一个参数之后的每个参数都被引用。所以到 shell 看到这样的命令:
cp '-r' './testdir1/*' './testdir2/'
问题是通配符(*
)文件系统在testdir1
目录中查找字面名称为“*
”的文件,当然,不存在。
解决方案是使用shell = True
选项进行类似于所选答案的调用,并且没有引用任何参数。
我知道shell=True
的选项可能很诱人,但由于security issues,它总是不可取的。
对于Python 3.5 或更高版本:
import subprocess
import glob
subprocess.run(['cp', '-r'] + glob.glob('./testdir1/*') + ['./testdir2/'])
对于Python 3.4 或更低版本:
import subprocess
import glob
subprocess.call(['cp', '-r'] + glob.glob('./testdir1/*') + ['./testdir2/'])
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(63条)