user1649114
user1649114

Reputation: 33

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

Upvotes: 0

Views: 781

Answers (2)

user1649114
user1649114

Reputation: 33

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

Upvotes: 2

Doseph
Doseph

Reputation: 199

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()

Upvotes: 1

Related Questions