Pass parameters to python plumbum command from a list

1.1k Views Asked by At

I'm using Plumbum to run command line utilities in the foreground on Python. if you had a command foo x y z, you would run it from Plumbum like so:

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. I could not figure out how to unpack this list to send it as parameters to plumbum. Any suggestions?

4

There are 4 best solutions below

0
On BEST ANSWER

Turns out I could have used __getitem__ for this. All I had to do was:

from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo.__getitem__(params) & FG
0
On

This seems to work:

from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo(*params) & FG
0
On

Thanks for the answer Alon Mysore, happened to be what I needed.

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):

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.

0
On

Rather than use __getitem__, a more readable (and equivalent) solution is bound_command:

from plumbum import cmd, FG
params = ['x', 'y', 'z']
cmd.foo.bound_command(params) & FG