Jim
Jim

Reputation: 125

Have command line argument as a default function argument

I have a script I'm running (with a package of modules I wrote) and in some part a certain script executes another with a command line argument. I want the other script (which is exposed to other people, as the others aren't but this one is modifiable & view-able by users) to automatically transfer sys.argv[1] to a certain function, say foo(), which has some argument that the user sends when calling it - but I don't want the user to know about the extra argument and need to send it himself (in other words, I want sys.argv[1] to be automatically sent to foo()).

Is this possible?

Example:

#my_script.py#
import subprocess
def do_stuff():
    #stuff
    return calculated_var
my_var = do_stuff()
subprocess.check_call(["C:/path/to/user/script/user_script.py", str(my_var)])

#user_script.py#
import my_module
print "My script was finally called, I don't know about any arguments"
my_module.my_func(my_var1, my_var2) #In the background, both my_var1 and my_var 2 are called as function arguments BUT also sys.argv[1] without the user knowing

#my_module.py#
def my_func(arg1, arg2, arg3="""WHAT DO I PUT HERE? I can't put sys.argv[1]"""):
   pass

Upvotes: 0

Views: 80

Answers (1)

vesche
vesche

Reputation: 1860

What you described should work. Here it is boiled down, hope it helps.

my_script.py:

import subprocess
subprocess.check_call(["python", "user_script.py", "c"])

user_script.py:

import my_module
my_module.my_func('a', 'b')

my_module.py:

import sys
def my_func(arg1, arg2, arg3=sys.argv[1]):
    print arg1, arg2, arg3

And then, python my_script.py will output a b c.

Upvotes: 2

Related Questions