简体   繁体   English

Python:全局名称re未在函数中定义

[英]Python: global name re is not defined in the function

I am relatively new to python and I am stumped by this error.我对 python 比较陌生,我被这个错误难住了。 I have a python script with three classes which imports re at the start.我有一个包含三个类的 python 脚本,它们在开始时导入 re。 But when I try to use re.search or re.sub within a function in the class it gives me the error "global name re is not defined ".但是当我尝试在类的函数中使用 re.search 或 re.sub 时,它给了我错误“全局名称 re 未定义”。 This is resolved when I write import re within the method.当我在方法中编写 import re 时,此问题已解决。

What am I doing wrong?我究竟做错了什么?

import re
class Temp:
    def pluginSysLog(self):
        import re
        folderName= "plugin" 
        fileName=inspect.stack()[1][1].split("/")[len(inspect.stack()[1][1].split("/"))-1]                
        logObject = temp.loggerSetup("logObject", "/"+folderName+"/"+re.sub(".py",".log",fileName))       
        return logObject 

Error错误

File "./temp.py", line 151, in pluginSysLog
    logObject = temp.loggerSetup("logObject", "/"+folderName+"/"+re.sub(".py",".log",fileName))       
NameError: global name 're' is not defined

Not sure without more code, but:不确定没有更多代码,但是:

1) If you've imported re at the top of the file, at the global level, you don't need to re-import within any classes or functions in that file 1) 如果您在文件的顶部,在全局级别导入了 re,则不需要在该文件中的任何类或函数中重新导入

2) Be careful you haven't created any variables, function parameters, member variables, etc. with the name "re". 2)注意你没有创建任何名称为“re”的变量、函数参数、成员变量等。

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

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