使用“cp”时出现Python子进程错误

2024-05-17 06:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用子进程调用执行复制操作(代码如下):

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和Python2.6

注意,我读了Problems with issuing cp command with Popen in Python中的问题,它建议使用shell = True选项,这对我不起作用,正如我所提到的:


Tags: 代码importtrue进程错误withshellcall
2条回答

使用shell=True时,向subprocess.call传递字符串而不是列表:

subprocess.call('cp -r ./testdir1/* ./testdir2/', shell=True)

The docs say

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

因此(在Unix上),当一个列表被传递到subprocess.Popen(或subprocess.call)时,列表的第一个元素被解释为命令,列表中的所有其他元素都被解释为shell的参数。因为在您的情况下,不需要向shell传递参数,所以您只需传递一个字符串作为第一个参数。

这是个老问题,但我也有同样的问题。

你打这个电话遇到的问题是:

subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = False)

是指每一个参数后的第一个都被引用。对于shell,可以看到这样的命令:

cp '-r' './testdir1/*' './testdir2/'

这个问题是通配符(*)。文件系统在testdir1目录中查找一个文本名为*的文件,当然,该目录不存在。

解决方案是使用shell = True选项和不引用任何参数使调用与所选答案类似。

相关问题 更多 >