简体   繁体   English

python导入模块全局本地名称空间

[英]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 我有一个包含的Python脚本MyScipt.py

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 PS D:\\ xxx \\ python> python。\\ myScript.py等等等等追溯(最近一次调用):文件“。\\ myScript.py”,第288行,位于主rootDir = sys.argv [1] IndexError:列表索引超出范围

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 追溯(最近一次通话最后一次):main()中的文件“。\\ myScript.py”,行299,主用法中的文件“。\\ myScript.py”,行290(0)文件“。\\ myScript.py”第15行,用法sys.exit()NameError:未定义名称'sys'

If I uncomment the 2nd line (# import sys), it'll work 如果我取消注释第二行(#import sys),它将起作用

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 必须将import sys语句放在脚本的开头才能解决此错误

Just import sys at the top of the file instead of in the function. 只需在文件顶部而不是函数中导入sys。

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() 您收到第二个错误,因为没有将任何参数传递给脚本,然后未定义sys,因此无法sys.exit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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