简体   繁体   English

我如何正则表达式搜索python值? “”“字符串”“”,“字符串”,“字符串”,(元组),[列表],{dict}

[英]How do I regex search for python values? “”“string”“”, “string”, 'string', (tuple), [list], {dict}

I'm trying to extract variables/values from a Django settings.py file (preserving comments, whitespace, etc.) and move or append them to another file programmatically using Python. 我正在尝试从Django settings.py文件中提取变量/值(保留注释,空格等),然后使用Python以编程方式将其移动或附加到另一个文件中。 Overall, I'm trying to split up the settings module into several files automatically (not manually using a text editor). 总体而言,我正在尝试将设置模块自动拆分为多个文件(而不是使用文本编辑器手动进行)。

How do I find the value assigned to any variable in such a file? 如何在这样的文件中找到分配给任何变量的值? - If possible in a concise way, eg using regular expressions. -如果可能的话,以简洁的方式,例如使用正则表达式。

Example variables/values: 示例变量/值:

DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [
    '*'
]
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_PATH, 'database.sqlite'),
    }
}
SECRET_KEY = '#*ji*0hbpj6#4-0=$%bl(z+z)c=pd(rn^9u*1_96f^ba+4w58v'
LONG_STRING_VALUE = \
"""
bla foo bar baz ...
"""
A_TUPLE = (
    '...',
)

Notes: 笔记:

  • I read the file as one long string, therefore regex matches can span several lines. 我将文件读为一个长字符串,因此正则表达式匹配项可以跨越多行。
  • No need to fully parse/understand the value, just find the closing delimiter. 无需完全解析/理解值,只需找到结束定界符即可。
  • I'm wondering if the code of the Python interpreter is available (as a Python module) that parses values in Python code. 我想知道Python解释器的代码是否可用(作为Python模块)来解析Python代码中的值。 Anybody knowing? 有人知道吗?
  • Partially working code is on GitHub: DjangoSettingsManager (identifies any variable until after equal sign, as of 15-feb-2014) 部分有效的代码在GitHub上: DjangoSettingsManager (标识所有变量,直到等号后,截至2014年2月15日)

     r'([ ]*#.*\\n)*[ ]*(\\A|\\b)' + var + r'\\s*=\\s*\\\\?\\s*' 

正则表达式可视化

Test this w/ Debuggex 使用Debuggex进行测试

Use django.conf.settings module, for instance you can know is django is in debug mode or not typing: 使用django.conf.settings模块,例如,您可以知道django处于调试模式还是未键入:

from django.conf import settings

settings.DEBUG
...

Doc here Doc 在这里

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

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