11

在我当前的工作目录中,我有目录 ROOT/ 里面有一些文件。

我知道我可以执行cp -r ROOT/* /dst并且我没有问题。

但是如果我打开我的 Python 控制台并写下这个:

import subprocess
subprocess.call(['cp', '-r', 'ROOT/*', '/dst'])

它不起作用!

我有这个错误:cp: cannot stat ROOT/*: No such file or directory

你能帮助我吗?

4

4 回答 4

10

Just came across this while trying to do something similar.

The * will not be expanded to filenames

Exactly. If you look at the man page of cp you can call it with any number of source arguments and you can easily change the order of the arguments with the -t switch.

import glob
import subprocess
subprocess.call(['cp', '-rt', '/dst'] + glob.glob('ROOT/*'))
于 2011-02-18T11:10:52.430 回答
7

尝试

subprocess.call('cp -r ROOT/* /dst', shell=True)

注意这里使用单个字符串而不是数组。

或者使用listdir构建自己的实现并复制

于 2009-09-08T09:16:02.917 回答
4

*不会扩展为文件名。这是外壳的功能。在这里,您实际上想要复制一个名为 *. subprocess.call()与参数一起使用shell=True

于 2009-09-08T08:49:23.570 回答
0

提供命令作为列表而不是字符串 + 列表。

以下两个命令相同:-

First Command:-
test=subprocess.Popen(['rm','aa','bb'])

Second command:-
list1=['rm','aa','bb']
test=subprocess.Popen(list1)

因此,要复制多个文件,需要使用 blob 获取文件列表,然后将“cp”添加到列表的前面,将目标添加到列表的末尾,并将列表提供给 subprocess.Popen()。

喜欢:-

list1=blob.blob("*.py")
list1=['cp']+list1+['/home/rahul']
xx=subprocess.Popen(list1)

它会完成这项工作。

于 2011-11-07T13:00:58.763 回答