def expandvars(path):
if '<STR_LIT:$>' not in path and '<STR_LIT:%>' not in path:<EOL><INDENT>return path<EOL><DEDENT>import string<EOL>varchars = string.ascii_letters + string.digits + '<STR_LIT>'<EOL>if isinstance(path, _unicode):<EOL><INDENT>encoding = sys.getfilesystemencoding()<EOL>def getenv(var):<EOL><INDENT>return os.environ[var.encode(encoding)].decode(encoding)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def getenv(var):<EOL><INDENT>return os.environ[var]<EOL><DEDENT><DEDENT>res = '<STR_LIT>'<EOL>index = <NUM_LIT:0><EOL>pathlen = len(path)<EOL>while index < pathlen:<EOL><INDENT>c = path[index]<EOL>if c == '<STR_LIT>':   <EOL><INDENT>path = path[index + <NUM_LIT:1>:]<EOL>pathlen = len(path)<EOL>try:<EOL><INDENT>index = path.index('<STR_LIT>')<EOL>res = res + '<STR_LIT>' + path[:index + <NUM_LIT:1>]<EOL><DEDENT>except ValueError:<EOL><INDENT>res = res + c + path<EOL>index = pathlen - <NUM_LIT:1><EOL><DEDENT><DEDENT>elif c == '<STR_LIT:%>':  <EOL><INDENT>if path[index + <NUM_LIT:1>:index + <NUM_LIT:2>] == '<STR_LIT:%>':<EOL><INDENT>res = res + c<EOL>index = index + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>path = path[index+<NUM_LIT:1>:]<EOL>pathlen = len(path)<EOL>try:<EOL><INDENT>index = path.index('<STR_LIT:%>')<EOL><DEDENT>except ValueError:<EOL><INDENT>res = res + '<STR_LIT:%>' + path<EOL>index = pathlen - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>var = path[:index]<EOL>try:<EOL><INDENT>res = res + getenv(var)<EOL><DEDENT>except KeyError:<EOL><INDENT>res = res + '<STR_LIT:%>' + var + '<STR_LIT:%>'<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif c == '<STR_LIT:$>':  <EOL><INDENT>if path[index + <NUM_LIT:1>:index + <NUM_LIT:2>] == '<STR_LIT:$>':<EOL><INDENT>res = res + c<EOL>index = index + <NUM_LIT:1><EOL><DEDENT>elif path[index + <NUM_LIT:1>:index + <NUM_LIT:2>] == '<STR_LIT:{>':<EOL><INDENT>path = path[index+<NUM_LIT:2>:]<EOL>pathlen = len(path)<EOL>try:<EOL><INDENT>index = path.index('<STR_LIT:}>')<EOL>var = path[:index]<EOL>try:<EOL><INDENT>res = res + getenv(var)<EOL><DEDENT>except KeyError:<EOL><INDENT>res = res + '<STR_LIT>' + var + '<STR_LIT:}>'<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>res = res + '<STR_LIT>' + path<EOL>index = pathlen - <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>var = '<STR_LIT>'<EOL>index = index + <NUM_LIT:1><EOL>c = path[index:index + <NUM_LIT:1>]<EOL>while c != '<STR_LIT>' and c in varchars:<EOL><INDENT>var = var + c<EOL>index = index + <NUM_LIT:1><EOL>c = path[index:index + <NUM_LIT:1>]<EOL><DEDENT>try:<EOL><INDENT>res = res + getenv(var)<EOL><DEDENT>except KeyError:<EOL><INDENT>res = res + '<STR_LIT:$>' + var<EOL><DEDENT>if c != '<STR_LIT>':<EOL><INDENT>index = index - <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>res = res + c<EOL><DEDENT>index = index + <NUM_LIT:1><EOL><DEDENT>return res<EOL>
Expand shell variables of the forms $var, ${var} and %var%.

    Unknown variables are left unchanged.