sys.argv in main() but referencing global var in a previous function

python pass by reference example
python pass function as argument with parameters
python pass arguments to script
python pass string by reference
python 3 command line arguments
python pass object to function
python pass by value
python pass function name as argument

Trying to find a pythonic way to work around the UnboundLocalError. In this example file, I want to be able to import functions to another python script (so I can't declare thisfile,flag1 before main()). The string = is just a way to show that I want to use flag1 as a local variable.

What's a good work-around? (I'd rather not access flag1 by indexing sys.argv[1]. Just my preference.)

def somefunction(flag1=flag1):
    string = "I just want to use the flag1 var (%(flag1)s)" % locals()
def main():
    somefunction()

if __name__ == '__main__':
    thisfile, flag1 = sys.argv
    main()

=====
OUT: UnboundLocalError: local variable 'flag1' referenced before assignment

UPDATE: So, what I didn't say is what I'm actually doing in somefunction - there I'm creating an sbatch file with a general skeleton and filling in variables, so I'll need flag1 to be local, and I'd rather not pass it along through a bunch of functions, or make multiple strings if possible (it looks prettier this way).

def somefunction():
    sometext = gettext()
    firstvar  = getfirstvar()
    string = '''!/bin/bash
#SBATCH --flags

./some_program --generic-flag 18 --used-every-time /some/path \
--needed-var %(sometext)s --first-var %(firstvar)s \
--final-flag %(flag1)s
''' % locals()

def main():
    somefunction()

if __name__ == '__main__':
    thisfile, flag1 = sys.argv
    main()

You'll need to somehow pass the variable in. Below is one way to do it, verified to work (BSD).

def somefunction(flag1=""):
    string = "I just want to use the flag1 var (%s)" % flag1
    print(string)

def main(flag1=""):
    somefunction(flag1=flag1)

if __name__ == "__main__":
    import sys 
    thisfile, flag1 = sys.argv
    main(flag1)

Python Tutorial: Passing Arguments, If you call the function ref_demo() of the previous example - like we do in the So, when we are back in the main scope x has still the original value 9 and the id In other words, Python initially behaves like call-by-reference, but as soon as we or more global variables, which have been passed as arguments to a function. 0 sys.argv in main() but referencing global var in a previous function Mar 13 '19 0 split file by lines into many different files - name each file with index of original file Nov 30 '15 0 avoid R loop and parallelize with snow Jun 16 '17

A neater way would be to access default flag1 only where it is needed

def somefunction(flag1=None):
    if flag1 is None:
        flag1 = sys.argv[1]
    string = "I just want to use the flag1 var (%(flag1)s)" % locals()

Python2 Tutorial: Passing Arguments, The passing of parameters and arguments in Python. They are also passed by object reference, but they can be changed in place in the function. So, when we are back in the main scope x has still the original value 9. We learn from the previous example that the arguments passed to the function call of varpafu() are� len(sys.argv) is the total number of length of command-line arguments. Here sys.argv[0] is the program, i.e. script name. If you are going to work with command-line arguments, you probably want to use sys.argv. Python Sys.argv. Let’s take the example of sys.argv command and see the output of the following program.

locals().update() seems to work well enough, and I don't have to pass along the var through a bunch of functions to where I actually use it.

Any further improvements welcomed.

def somefunction():
    locals().update({'thisfile':thisfile,'flag1':flag1})
    sometext = gettext()
    firstvar  = getfirstvar()
    string = '''!/bin/bash
#SBATCH --flags

./some_program --generic-flag 18 --used-every-time /some/path \
--needed-var %(sometext)s --first-var %(firstvar)s \
--script-used %(thisfile)s \
--final-flag %(flag1)s
''' % locals()

def main():
    somefunction()

if __name__ == '__main__':
    global thisfile,flag1
    thisfile, flag1 = sys.argv
    main()

28.1. sys — System-specific parameters and functions — Python 2.7 , After calling this function, exc_info() will return three None values until another exception is raised in the current thread or the execution stack� # sys.argv[0] is the script name itself and can be ignored # Standard boilerplate to call the main() function to begin # the program. if __name__ == '__main__': main() Answers: I would like to note that previous answers made many assumptions about the user’s knowledge.

Python Tutorial, You can use space or tab for indentation (but not mixture of both). Run the main() function if __name__ == '__main__': main() The command-line arguments are stored in a variable sys.argv , which is a list (Python's dynamic You can use built-in function type(var_name) to get the object type referenced by a variable. The following are 40 code examples for showing how to use sys.argv().These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

Python Command Line Arguments – Real Python, Line 4 defines main() , which is the entry point of a C program. You can parse the Python command line arguments in sys.argv without For a given input, a hash function always returns the same value. In a short script, you can safely rely on the global access to sys.argv , but in a larger program, you� The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes − sys.argv is the list of command-line arguments. len(sys.argv) is the number of command-line arguments. Here sys.argv[0] is the program ie. script name. Example. Consider the following script test.py −

The 10 Most Common Mistakes That Python Developers Make, Python allows you to specify that a function argument is optional by providing a In the above code, for example, one might expect that calling foo() repeatedly (i.e. , But what happens if we attempt to import b.py (without having previously the interpreter shuts down, the module's global variables are all set to None . When you run a python script any arguments you provide to the script are captured by Python and placed in a list called sys.argv So if you run [code]python my_script.py Hello Goodbye [/code]Then inside my_script.py : [code]sys.argv[0] == ‘my_scrip

Comments
  • OP said he wants to import the function elsewhere, this will not work on imports.