0

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

2
  • 1
    why not importing import sys at toplevel before all function definitions? Commented Jul 15, 2017 at 12:57
  • Indeed it was the initial position I want to write the code but then I got messed up with 'where should I place the call to import os.path'. I'll mark this question as answer and probably open a new one. Thanks Commented Jul 15, 2017 at 16:06

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

You're right. This is where I wanted to put it first but things got messy while trying to use os.path method. I think I should open another question. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.