简体   繁体   中英

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. 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. Anybody knowing?
  • Partially working code is on GitHub: DjangoSettingsManager (identifies any variable until after equal sign, as of 15-feb-2014)

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

正则表达式可视化

Test this w/ Debuggex

Use django.conf.settings module, for instance you can know is django is in debug mode or not typing:

from django.conf import settings

settings.DEBUG
...

Doc here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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