python subprocess.call 的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1392757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:07:56  来源:igfitidea点击:

Problem with subprocess.call

pythonsubprocess

提问by

In my current working directory I have the dir ROOT/ with some files inside.

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

I know I can exec cp -r ROOT/* /dstand 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?

你能帮助我吗?

回答by chetbox

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 cpyou can call it with any number of source arguments and you can easily change the order of the arguments with the -tswitch.

确切地。如果您查看手册页,cp您可以使用任意数量的源参数调用它,并且您可以使用-t开关轻松更改参数的顺序。

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

回答by Alice Purcell

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 listdirand copy

或者使用listdircopy构建您自己的实现

回答by Alice Purcell

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.

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

回答by Rahul

Provide the command as list instead of the string + 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.

它会完成工作。