1

In my script I call an executable with optional command line argument (if passed, this argument switches on a function in the executable, which is off by default). I want to control this option directly from argument of the script itself. Write now I do:

import subprocess option = False if option: check = subprocess.Popen(['executable', '--option']) else: check = subprocess.Popen(['executable']) 

I tried to find a more compact way:

import subprocess option = False check = subprocess.Popen(['executable', '--option' if option else '']) 

But this raises error "Unknown option" in the exactable itself.

And this raises error in python:

import subprocess option = False check = subprocess.Popen(['executable', '--option' if option else None]) 

So, my question: is there a way to pass an optional argument to subprocess in one line?

2 Answers 2

6

An alternative that's IMO more readable than the current suggestion is using list unpacking:

*(['--opt=val'] if opt else []) 

And with your example:

check = subprocess.Popen([ 'executable', *(['--option'] if option else []) ]) 
Sign up to request clarification or add additional context in comments.

Comments

2

Using list slicing:

>>> ['executable', '--option'][:1 + False] ['executable'] >>> ['executable', '--option'][:1 + True] ['executable', '--option'] >>> False == 0 True >>> True == 1 True 

check = subprocess.Popen(['executable', '--option'][:1 + option]) 

UPDATE Alternative

You can also use list * bool:

>>> ['a'] * True ['a'] >>> ['a'] * False [] 

Using this, you can combine multiple options:

check = subprocess.Popen(['executable'] + ['-option1'] * option1 + ['-option2'] * option2) 

2 Comments

And if there are several such options (e.g. executable [--option1] [--option2] ...)?
@Roman, Assuming option variable is a boolean object, you can use alternative list * bool: subprocess.Popen(['executable'] + ['-option1'] * option1 + ['-option2'] * option2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.