简体   繁体   中英

python import module global local namespace

I have a problem understanding how import is working when call in function. I believe it's related to scope but I can't figure out how it works. I've checked similar questions on the site or some tutorials but it looks like I just don't understand how it works

I have a python script MyScipt.py containing

def usage(errorID):
    # import sys
    if errorID == 0:
        print("blah blah blah")
    print("blah blah blah")
    print("blah blah blah"+\
    sys.exit()

def main():
    import sys
    # print(len(sys.argv),sys.argv)
    try:
        rootDir = sys.argv[1]
    except IndexError:
        usage(0)

# MAIN PROGRAM
#
if __name__ =="__main__":
    main()

the execution is failing with

PS D:\\xxx\\python> python .\\myScript.py blah blah blah blah blah blah blah blah blah Traceback (most recent call last): File ".\\myScript.py", line 288, in main rootDir = sys.argv[1] IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File ".\\myScript.py", line 299, in main() File ".\\myScript.py", line 290, in main usage(0) File ".\\myScript.py", line 15, in usage sys.exit() NameError: name 'sys' is not defined

If I uncomment the 2nd line (# import sys), it'll work

How can I make an import available to all function within my script?

Thanks in advance

Thanks all for your feedback. import sys statement must be placed at the beginning of the script to solve this error

Just import sys at the top of the file instead of in the function.

import sys
def usage(errorID):

    if errorID == 0:
        print("blah blah blah")
    print("blah blah blah")
    print("blah blah blah"+\
    sys.exit()

def main():
    import sys
    # print(len(sys.argv),sys.argv)
    try:
        rootDir = sys.argv[1]
    except IndexError:
        usage(0)

# MAIN PROGRAM
#
if __name__ =="__main__":
    main()

You are getting the second error because you are not passing any arguments to the script and then sys is not defined so you cannot sys.exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM