Yifu Yu Yifu Yu - 6 months ago 39
Python Question

python subprocess.popen use preexec_fn with arguments

I have read the python document about subprocess, but the argument

preexec_fn
for
subprocess.Popen
can only point to a function with no argument.

Now I want to call a function with two arguments just like what
preexec_fn
do, I've tried to use global variables, but it doesn't work. So how can I do? Thanks a lot.

Sorry for my bad english.

Answer

You can pass the arguments using functools.partial or a lambda:

>>> import functools
>>> def need_two_arguments(a,b):
...     print a + b
... 
>>> no_arguments_needed = functools.partial(need_two_arguments, "Hello, ", "World!")
>>> no_arguments_needed()
Hello, World!
>>> no_arguments_needed = (lambda: need_two_arguments("Hello, ", "World!"))
>>> no_arguments_needed()
Hello, World!
Comments