Sunday, October 06, 2019

Re: python help needed - os.environ \u [was Re: WIP: arouteserver]

On Sun, Oct 06, 2019 at 06:16:17PM +0100, Stuart Henderson wrote:
> So it turns out this is from the code where it substitutes ${FOO} with the
> contents of the environment variable FOO (this was added in
> https://github.com/pierky/arouteserver/commit/a184b428)
>
> def expand_env_vars(doc):
> res = doc
> for v in os.environ:
> res = re.sub("\$\{" + v + "\}", os.environ[v], res)
> res = re.sub("\$\{[A-Za-z0-9_]+\}", "", res)
> return res
>
> if the environment contains e.g.
>
> PS1=<\u@\h:\w:!>\$
>
> then this triggers the bug:
>
> > :Traceback (most recent call last):
> > : File "/usr/local/lib/python3.7/sre_parse.py", line 1021, in parse_template
> > : this = chr(ESCAPES[this][1])
> > :KeyError: '\\u'
> > :
> > :During handling of the above exception, another exception occurred:
...
> > :re.error: bad escape \u at position 1
>
> Python people - do you have any suggestions how to deal with this please?
Python's re module has an escape function that should be used in the
call to re.sub(), I think:

$ PS1='\u' python3 -c 'import os, re; print(re.escape(os.environ["PS1"]))'
\\u

No comments:

Post a Comment