[Tutor] Turning multiple Popen calls into a function

Eric Walstad eric at ericwalstad.com
Thu Nov 1 19:20:13 CET 2007


Hi Jay...
jay wrote:
...
> I would be sending an arbitrary number of PIPES with each function call.
> 
> I'm a little stumped as to how to handle the variables.  If I have an 
> arbitrary number of PIPES, how do I declare my variables (p1, p2, p3, 
> etc...) ahead of time in the function??
> 
> Thanks for any suggestions!


 >>> def foo(bar, *fizz, **bang):
...     print "bar:", bar
...     print "fizz:", fizz
...     print "bang:", bang
...

 >>> foo('and now for something completely different')
bar: and now for something completely different
fizz: ()
bang: {}

 >>> foo('hello', 'and', 'cows', 'eat', 'grass')
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {}

 >>> foo('hello', 'and', 'cows', 'eat', 'grass', greeting='hello', 
location='world')
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {'greeting': 'hello', 'location': 'world'}

 >>> a_tuple = ('and', 'cows', 'eat', 'grass')
 >>> a_dict = dict(greeting='hello', location='world')
 >>> foo('hello', *a_tuple, **a_dict)
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {'location': 'world', 'greeting': 'hello'}


Or, just pass the pipes in as an iterable to your function:
def pipe_handler(pipes):
     for n, pipe in enumerate(pipes):
         print "Pipe %d: '%s'" % (n, pipe)

pipes = []
pipes.append(some_pipe)
...
pipe_handler(pipes)

See also:
<http://docs.python.org/tut/node6.html#SECTION006700000000000000000>

I hope that helps,

Eric


More information about the Tutor mailing list