简体   繁体   English

subprocess.call问题

[英]Problem with subprocess.call

In my current working directory I have the dir ROOT/ with some files inside. 在我当前的工作目录中,我的目录是ROOT /,其中包含一些文件。

I know I can exec cp -r ROOT/* /dst and I have no problems. 我知道我可以执行cp -r ROOT/* /dst并且没有问题。

But if I open my Python console and I write this: 但是,如果我打开Python控制台并编写以下代码:

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

It doesn't work! 没用!

I have this error: cp: cannot stat ROOT/*: No such file or directory 我有此错误: cp: cannot stat ROOT/*: No such file or directory

Can you help me? 你能帮助我吗?

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. 如果查看cp的手册页,则可以使用任意数量的源参数调用它,并且可以使用-t开关轻松更改参数的顺序。

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

Try 尝试

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

Note the use of a single string rather than an array here. 请注意,此处使用单个字符串而不是数组。

Or build up your own implementation with listdir and copy 或者使用listdir建立自己的实现并复制

The * will not be expanded to filenames. *不会扩展为文件名。 This is a function of the shell. 这是外壳的功能。 Here you actually want to copy a file named *. 在这里,您实际上要复制一个名为*的文件。 Use subprocess.call() with the parameter shell=True . subprocess.call()与参数shell=True

Provide the command as list instead of the string + list. 提供命令作为列表,而不是字符串+ list。

The following two commands are same:- 以下两个命令相同:

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

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

So to copy multiple files, one need to get the list of files using blob and then add 'cp' to the front of list and destination to the end of list and provide the list to subprocess.Popen(). 因此,要复制多个文件,需要使用blob获取文件列表,然后将“ cp”添加到列表的开头,将目的地添加到列表的末尾,并将列表提供给subprocess.Popen()。

Like:- 喜欢:-

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

It will do the work. 它将完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM