Pregunta

I'm getting stuck with this

I have a python file which is imported from elsewhere as a module, in order to use some functions provided by it. I'm trying a way to call it form CLI, giving it 0 or 5 arguments.

def simulate(index, sourcefile, temperature_file, save=0, outfile='fig.png'):
    (...)
    # do calculations and spit a nice graph file.

if __name__ == '__main__':

    if (len(sys.argv) == 6 ):
        # ugly code alert
        simulate(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    else:
        (...)
        #do some other things and don't bother me

I was wondering if there's a clean way to pass all but first argument to a function. I tried simulate(sys.argv[1:]) but it throws a single object (list), and since simulate function expects 4 arguments, it doesn't work: TypeError: 'simulate() takes at least 3 arguments (1 given)' Tried also with simulate(itertools.chain(sys.argv[1:])) with same result.

Since this file is imported elsewhere as a module and this function is being called many times, it seems a bad idea to change the function's signature to recieve a single argument

¿Fue útil?

Solución

Otros consejos

What you want to use is called "Packing/Unpacking" in Python:

foo(*sys.argv)

See: http://en.wikibooks.org/wiki/Python_Programming/Tuples#Packing_and_Unpacking

If you want "all but first argument":

foo(*sys.argv[1:])

This is called "slicing". See: http://docs.python.org/2.3/whatsnew/section-slices.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top