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
import sysat toplevel before all function definitions?import os.path'. I'll mark this question as answer and probably open a new one. Thanks