[英]Pass parameters to python plumbum command from a list
I'm using Plumbum to run command line utilities in the foreground on Python.我正在使用Plumbum在 Python 的前台运行命令行实用程序。 if you had a command
foo xyz
, you would run it from Plumbum like so:如果你有一个命令
foo xyz
,你可以像这样从 Plumbum 运行它:
from plumbum import cmd, FG
cmd.foo['x', 'y', 'z'] & FG
In the code I'm writing however, the parameters ['x', 'y', 'z']
are generated into a list.然而,在我正在编写的代码中,参数
['x', 'y', 'z']
被生成到一个列表中。 I could not figure out how to unpack this list to send it as parameters to plumbum.我不知道如何解压这个列表以将它作为参数发送给 plumbum。 Any suggestions?
有什么建议吗?
Turns out I could have used __getitem__
for this.原来我可以用
__getitem__
这个。 All I had to do was:我所要做的就是:
from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo.__getitem__(params) & FG
Thanks for the answer Alon Mysore, happened to be what I needed.感谢 Alon Mysore 的回答,恰好是我需要的。
I tried the following, (did NOT work):我尝试了以下操作(无效):
from plumbum import local
from plumbum.commands import ProcessExecutionErr
files = ['gs://some-repo/somefile.txt', 'gs://some-repo/somefile2.txt']
files_string = ' '.join(files)
gsutil = local['gsutil']
command = gsutil['-m', 'rm', files_string]
try:
job = command.run()
except ProcessExecutionError as err:
print('Error: {}'.format(err))
sys.exit(1)
But after your answer, here's another example for people reference using gsutil (DID Work):但是在您回答之后,这是另一个使用 gsutil (DID Work) 供人们参考的示例:
from plumbum import local
from plumbum.commands import ProcessExecutionError
files = ['gs://some-repo/somefile.txt', 'gs://some-repo/somefile2.txt']
gsutil = local['gsutil']
command = gsutil['-m', 'rm']
try:
job = command.__getitem__(files).run()
except ProcessExecutionError as err:
print('Error: {}'.format(err))
sys.exit(1)
The issue being that plumbum didn't seem to play nice when I concat'd the list into a string myself.问题是当我自己将列表连接成一个字符串时,铅弹似乎不太好。
This seems to work:这似乎有效:
from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo(*params) & FG
Rather than use __getitem__
, a more readable (and equivalent) solution is bound_command
:而不是使用
__getitem__
,一个更具可读性(和等效)的解决方案是bound_command
:
from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo.bound_command(params) & FG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.