We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
In .xonshrc, import does not create a global name
xonsh: git checkout f44013b31756ba5491f2a7e1dffb7ad64513b28e
python: 3.4.1
OS: Fedora 21

With this as your .xonshrc:

``` python
import subprocess

def get_tty():
    tty = subprocess.check_output('tty').decode().strip()
    segments = tty.split('/')
    return '/'.join(segments[-2:])

$PROMPT='{tty}@{{hostname}}$ '.format(tty=get_tty())
```

Trying to start .xonshrc yields a traceback:

```
Traceback (most recent call last):
  File "scripts/xonsh", line 3, in <module>
    main()
  File "/srv/git/wishlist/xonsh/xonsh/main.py", line 36, in main
    shell = Shell()
  File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 94, in __init__
    execer=self.execer)
  File "/srv/git/wishlist/xonsh/xonsh/environ.py", line 168, in xonshrc_context
    execer.exec(rc, glbs={}, locs=env)
  File "/srv/git/wishlist/xonsh/xonsh/execer.py", line 110, in exec
    return exec(code, glbs, locs)
  File "/home/badger/.xonshrc", line 7, in <module>

  File "/home/badger/.xonshrc", line 259, in get_tty
NameError: name 'subprocess' is not defined
Exception ignored in: <bound method Shell.__del__ of <xonsh.shell.Shell object at 0x7f383127e4e0>>
Traceback (most recent call last):
  File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 102, in __del__
    teardown_readline()
  File "/srv/git/wishlist/xonsh/xonsh/shell.py", line 65, in teardown_readline
    import readline
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2222, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 2164, in _find_spec
  File "<frozen importlib._bootstrap>", line 1940, in find_spec
  File "<frozen importlib._bootstrap>", line 1908, in _get_spec
TypeError: 'NoneType' object is not iterable
```

If I change .xonshrc to have the subprocess import inside of the function then it starts up fine.  So it seems like importing does not create a globally available name.  The other things I tried such as:

``` python
import subprocess as subprocess
subprocess = __import__('subprocess')
```

also lead to the same traceback.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `xonsh/environ.py`
Content:
```
1 """Environment for the xonsh shell.
2 """
3 import os
4 import re
5 import socket
6 import locale
7 import builtins
8 import platform
9 import subprocess
10 from warnings import warn
11 
12 from xonsh.tools import TERM_COLORS
13 
14 def current_branch(cwd=None):
15     """Gets the branch for a current working directory. Returns None
16     if the cwd is not a repository.  This currently only works for git, 
17     bust should be extended in the future.
18     """
19     branch = None
20     cwd = os.getcwd() if cwd is None else cwd
21 
22     # step out completely if git is not installed
23     try:
24         binary_location = subprocess.check_output(['which', 'git'], cwd=cwd,
25                                     stderr=subprocess.PIPE,
26                                     universal_newlines=True)
27         if not binary_location:
28             return branch
29     except subprocess.CalledProcessError:
30         return branch
31 
32     prompt_scripts = [
33         '/usr/lib/git-core/git-sh-prompt',
34         '/usr/local/etc/bash_completion.d/git-prompt.sh'
35     ]
36 
37     for script in prompt_scripts:
38         # note that this is about 10x faster than bash -i "__git_ps1"
39         _input = ('source {}; __git_ps1 "${{1:-%s}}"'.format(script))
40         try:
41             branch = subprocess.check_output(['bash',], cwd=cwd, input=_input,
42                                         stderr=subprocess.PIPE,
43                                         universal_newlines=True) or None
44         except subprocess.CalledProcessError:
45             continue
46 
47     # fall back to using the git binary if the above failed
48     if branch is None:
49         try:
50             s = subprocess.check_output(['git', 'rev-parse','--abbrev-ref', 'HEAD'],
51                     stderr=subprocess.PIPE, cwd=cwd,
52                     universal_newlines=True) 
53             s = s.strip()
54             if len(s) > 0:
55                 branch = s
56         except subprocess.CalledProcessError:
57             pass
58 
59     return branch
60 
61 
62 default_prompt = ('{BOLD_GREEN}{user}@{hostname}{BOLD_BLUE} '
63                   '{cwd}{BOLD_RED}{curr_branch} {BOLD_BLUE}${NO_COLOR} ')
64 default_title = '{user}@{hostname}: {cwd} | xonsh'
65 
66 def format_prompt(template=default_prompt):
67     """Formats a xonsh prompt template string.
68 
69     The following keyword arguments are recognized in the template string:
70 
71     + user -- Name of current user
72     + hostname -- Name of host computer
73     + cwd -- Current working directory
74     + curr_branch -- Name of current git branch (preceded by a space), if any
75     + (QUALIFIER\_)COLORNAME -- Inserts an ANSI color code
76         - COLORNAME can be any of:
77               BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE
78         - QUALIFIER is optional and can be any of:
79               BOLD, UNDERLINE, BACKGROUND, INTENSE,
80               BOLD_INTENSE, BACKGROUND_INTENSE
81     + NO_COLOR -- Resets any previously used color codes
82     """
83     env = builtins.__xonsh_env__
84     cwd = env['PWD']
85     branch = current_branch(cwd=cwd)
86     branch = '' if branch is None else ' ' + branch
87     p = template.format(
88             user=env.get('USER', '<user>'),
89             hostname=socket.gethostname(),
90             cwd=cwd.replace(env['HOME'], '~'),
91             curr_branch=branch,
92             **TERM_COLORS
93             )
94     return p
95 
96 
97 RE_HIDDEN = re.compile('\001.*?\002')
98 
99 def multiline_prompt():
100     """Returns the filler text for the prompt in multiline scenarios."""
101     curr = builtins.__xonsh_env__.get('PROMPT', "set '$PROMPT = ...' $ ")
102     curr = curr() if callable(curr) else curr
103     curr = format_prompt(curr)
104     line = curr.rsplit('\n', 1)[1] if '\n' in curr else curr
105     line = RE_HIDDEN.sub('', line)  # gets rid of colors
106     # most prompts end in whitespace, head is the part before that.
107     head = line.rstrip()
108     headlen = len(head)
109     # tail is the trailing whitespace
110     tail = line if headlen == 0 else line.rsplit(head[-1], 1)[1]
111     # now to constuct the actual string
112     dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT', '.')
113     dots = dots() if callable(dots) else dots
114     if dots is None or len(dots) == 0:
115         return ''
116     return (dots*(headlen//len(dots))) + dots[:headlen%len(dots)] + tail
117 
118 
119 BASE_ENV = {
120     'INDENT': '    ',
121     'PROMPT': default_prompt,
122     'TITLE': default_title,
123     'MULTILINE_PROMPT': '.',
124     'XONSHRC': os.path.expanduser('~/.xonshrc'),
125     'XONSH_HISTORY_SIZE': 8128,
126     'XONSH_HISTORY_FILE': os.path.expanduser('~/.xonsh_history'),
127     'LC_CTYPE': locale.setlocale(locale.LC_CTYPE),
128     'LC_COLLATE': locale.setlocale(locale.LC_COLLATE),
129     'LC_TIME': locale.setlocale(locale.LC_TIME),
130     'LC_MONETARY': locale.setlocale(locale.LC_MONETARY),
131     'LC_MESSAGES': locale.setlocale(locale.LC_MESSAGES),
132     'LC_NUMERIC': locale.setlocale(locale.LC_NUMERIC),
133     }
134 
135 if platform.system() == 'Darwin':
136     BASE_ENV['BASH_COMPLETIONS'] = []
137 else:
138     BASE_ENV['BASH_COMPLETIONS'] = ['/etc/bash_completion', 
139                                     '/usr/share/bash-completion/completions/git']
140 
141 def bash_env():
142     """Attempts to compute the bash envinronment variables."""
143     currenv = None
144     if hasattr(builtins, '__xonsh_env__'):
145         currenv = builtins.__xonsh_env__.detype()
146     try:
147         s = subprocess.check_output(['bash', '-i'], input='env', env=currenv, 
148                                     stderr=subprocess.PIPE,
149                                     universal_newlines=True)
150     except subprocess.CalledProcessError:
151         s = ''
152     items = [line.split('=', 1) for line in s.splitlines() if '=' in line]
153     env = dict(items)
154     return env
155 
156 def xonshrc_context(rcfile=None, execer=None):
157     """Attempts to read in xonshrc file, and return the contents."""
158     if rcfile is None or execer is None or not os.path.isfile(rcfile):
159         return {}
160     with open(rcfile, 'r') as f:
161         rc = f.read()
162     if not rc.endswith('\n'):
163         rc += '\n'
164     fname = execer.filename
165     env = {}
166     try:
167         execer.filename = rcfile
168         execer.exec(rc, glbs={}, locs=env)
169     except SyntaxError as err:
170         msg = 'syntax error in xonsh run control file {0!r}: {1!s}'
171         warn(msg.format(rcfile, err), RuntimeWarning)
172     finally:
173         execer.filename = fname
174     return env
175 
176 def default_env(env=None):
177     """Constructs a default xonsh environment."""
178     # in order of increasing precedence
179     ctx = dict(BASE_ENV)
180     ctx.update(os.environ)
181     ctx.update(bash_env())
182     if env is not None:
183         ctx.update(env)
184     return ctx
185
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/xonsh/environ.py b/xonsh/environ.py
--- a/xonsh/environ.py
+++ b/xonsh/environ.py
@@ -165,7 +165,7 @@
     env = {}
     try:
         execer.filename = rcfile
-        execer.exec(rc, glbs={}, locs=env)
+        execer.exec(rc, glbs=env)
     except SyntaxError as err:
         msg = 'syntax error in xonsh run control file {0!r}: {1!s}'
         warn(msg.format(rcfile, err), RuntimeWarning)

{"golden_diff": "diff --git a/xonsh/environ.py b/xonsh/environ.py\n--- a/xonsh/environ.py\n+++ b/xonsh/environ.py\n@@ -165,7 +165,7 @@\n     env = {}\n     try:\n         execer.filename = rcfile\n-        execer.exec(rc, glbs={}, locs=env)\n+        execer.exec(rc, glbs=env)\n     except SyntaxError as err:\n         msg = 'syntax error in xonsh run control file {0!r}: {1!s}'\n         warn(msg.format(rcfile, err), RuntimeWarning)\n", "issue": "In .xonshrc, import does not create a global name\nxonsh: git checkout f44013b31756ba5491f2a7e1dffb7ad64513b28e\npython: 3.4.1\nOS: Fedora 21\n\nWith this as your .xonshrc:\n\n``` python\nimport subprocess\n\ndef get_tty():\n    tty = subprocess.check_output('tty').decode().strip()\n    segments = tty.split('/')\n    return '/'.join(segments[-2:])\n\n$PROMPT='{tty}@{{hostname}}$ '.format(tty=get_tty())\n```\n\nTrying to start .xonshrc yields a traceback:\n\n```\nTraceback (most recent call last):\n  File \"scripts/xonsh\", line 3, in <module>\n    main()\n  File \"/srv/git/wishlist/xonsh/xonsh/main.py\", line 36, in main\n    shell = Shell()\n  File \"/srv/git/wishlist/xonsh/xonsh/shell.py\", line 94, in __init__\n    execer=self.execer)\n  File \"/srv/git/wishlist/xonsh/xonsh/environ.py\", line 168, in xonshrc_context\n    execer.exec(rc, glbs={}, locs=env)\n  File \"/srv/git/wishlist/xonsh/xonsh/execer.py\", line 110, in exec\n    return exec(code, glbs, locs)\n  File \"/home/badger/.xonshrc\", line 7, in <module>\n\n  File \"/home/badger/.xonshrc\", line 259, in get_tty\nNameError: name 'subprocess' is not defined\nException ignored in: <bound method Shell.__del__ of <xonsh.shell.Shell object at 0x7f383127e4e0>>\nTraceback (most recent call last):\n  File \"/srv/git/wishlist/xonsh/xonsh/shell.py\", line 102, in __del__\n    teardown_readline()\n  File \"/srv/git/wishlist/xonsh/xonsh/shell.py\", line 65, in teardown_readline\n    import readline\n  File \"<frozen importlib._bootstrap>\", line 2237, in _find_and_load\n  File \"<frozen importlib._bootstrap>\", line 2222, in _find_and_load_unlocked\n  File \"<frozen importlib._bootstrap>\", line 2164, in _find_spec\n  File \"<frozen importlib._bootstrap>\", line 1940, in find_spec\n  File \"<frozen importlib._bootstrap>\", line 1908, in _get_spec\nTypeError: 'NoneType' object is not iterable\n```\n\nIf I change .xonshrc to have the subprocess import inside of the function then it starts up fine.  So it seems like importing does not create a globally available name.  The other things I tried such as:\n\n``` python\nimport subprocess as subprocess\nsubprocess = __import__('subprocess')\n```\n\nalso lead to the same traceback.\n\n", "before_files": [{"content": "\"\"\"Environment for the xonsh shell.\n\"\"\"\nimport os\nimport re\nimport socket\nimport locale\nimport builtins\nimport platform\nimport subprocess\nfrom warnings import warn\n\nfrom xonsh.tools import TERM_COLORS\n\ndef current_branch(cwd=None):\n    \"\"\"Gets the branch for a current working directory. Returns None\n    if the cwd is not a repository.  This currently only works for git, \n    bust should be extended in the future.\n    \"\"\"\n    branch = None\n    cwd = os.getcwd() if cwd is None else cwd\n\n    # step out completely if git is not installed\n    try:\n        binary_location = subprocess.check_output(['which', 'git'], cwd=cwd,\n                                    stderr=subprocess.PIPE,\n                                    universal_newlines=True)\n        if not binary_location:\n            return branch\n    except subprocess.CalledProcessError:\n        return branch\n\n    prompt_scripts = [\n        '/usr/lib/git-core/git-sh-prompt',\n        '/usr/local/etc/bash_completion.d/git-prompt.sh'\n    ]\n\n    for script in prompt_scripts:\n        # note that this is about 10x faster than bash -i \"__git_ps1\"\n        _input = ('source {}; __git_ps1 \"${{1:-%s}}\"'.format(script))\n        try:\n            branch = subprocess.check_output(['bash',], cwd=cwd, input=_input,\n                                        stderr=subprocess.PIPE,\n                                        universal_newlines=True) or None\n        except subprocess.CalledProcessError:\n            continue\n\n    # fall back to using the git binary if the above failed\n    if branch is None:\n        try:\n            s = subprocess.check_output(['git', 'rev-parse','--abbrev-ref', 'HEAD'],\n                    stderr=subprocess.PIPE, cwd=cwd,\n                    universal_newlines=True) \n            s = s.strip()\n            if len(s) > 0:\n                branch = s\n        except subprocess.CalledProcessError:\n            pass\n\n    return branch\n\n\ndefault_prompt = ('{BOLD_GREEN}{user}@{hostname}{BOLD_BLUE} '\n                  '{cwd}{BOLD_RED}{curr_branch} {BOLD_BLUE}${NO_COLOR} ')\ndefault_title = '{user}@{hostname}: {cwd} | xonsh'\n\ndef format_prompt(template=default_prompt):\n    \"\"\"Formats a xonsh prompt template string.\n\n    The following keyword arguments are recognized in the template string:\n\n    + user -- Name of current user\n    + hostname -- Name of host computer\n    + cwd -- Current working directory\n    + curr_branch -- Name of current git branch (preceded by a space), if any\n    + (QUALIFIER\\_)COLORNAME -- Inserts an ANSI color code\n        - COLORNAME can be any of:\n              BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE\n        - QUALIFIER is optional and can be any of:\n              BOLD, UNDERLINE, BACKGROUND, INTENSE,\n              BOLD_INTENSE, BACKGROUND_INTENSE\n    + NO_COLOR -- Resets any previously used color codes\n    \"\"\"\n    env = builtins.__xonsh_env__\n    cwd = env['PWD']\n    branch = current_branch(cwd=cwd)\n    branch = '' if branch is None else ' ' + branch\n    p = template.format(\n            user=env.get('USER', '<user>'),\n            hostname=socket.gethostname(),\n            cwd=cwd.replace(env['HOME'], '~'),\n            curr_branch=branch,\n            **TERM_COLORS\n            )\n    return p\n\n\nRE_HIDDEN = re.compile('\\001.*?\\002')\n\ndef multiline_prompt():\n    \"\"\"Returns the filler text for the prompt in multiline scenarios.\"\"\"\n    curr = builtins.__xonsh_env__.get('PROMPT', \"set '$PROMPT = ...' $ \")\n    curr = curr() if callable(curr) else curr\n    curr = format_prompt(curr)\n    line = curr.rsplit('\\n', 1)[1] if '\\n' in curr else curr\n    line = RE_HIDDEN.sub('', line)  # gets rid of colors\n    # most prompts end in whitespace, head is the part before that.\n    head = line.rstrip()\n    headlen = len(head)\n    # tail is the trailing whitespace\n    tail = line if headlen == 0 else line.rsplit(head[-1], 1)[1]\n    # now to constuct the actual string\n    dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT', '.')\n    dots = dots() if callable(dots) else dots\n    if dots is None or len(dots) == 0:\n        return ''\n    return (dots*(headlen//len(dots))) + dots[:headlen%len(dots)] + tail\n\n\nBASE_ENV = {\n    'INDENT': '    ',\n    'PROMPT': default_prompt,\n    'TITLE': default_title,\n    'MULTILINE_PROMPT': '.',\n    'XONSHRC': os.path.expanduser('~/.xonshrc'),\n    'XONSH_HISTORY_SIZE': 8128,\n    'XONSH_HISTORY_FILE': os.path.expanduser('~/.xonsh_history'),\n    'LC_CTYPE': locale.setlocale(locale.LC_CTYPE),\n    'LC_COLLATE': locale.setlocale(locale.LC_COLLATE),\n    'LC_TIME': locale.setlocale(locale.LC_TIME),\n    'LC_MONETARY': locale.setlocale(locale.LC_MONETARY),\n    'LC_MESSAGES': locale.setlocale(locale.LC_MESSAGES),\n    'LC_NUMERIC': locale.setlocale(locale.LC_NUMERIC),\n    }\n\nif platform.system() == 'Darwin':\n    BASE_ENV['BASH_COMPLETIONS'] = []\nelse:\n    BASE_ENV['BASH_COMPLETIONS'] = ['/etc/bash_completion', \n                                    '/usr/share/bash-completion/completions/git']\n\ndef bash_env():\n    \"\"\"Attempts to compute the bash envinronment variables.\"\"\"\n    currenv = None\n    if hasattr(builtins, '__xonsh_env__'):\n        currenv = builtins.__xonsh_env__.detype()\n    try:\n        s = subprocess.check_output(['bash', '-i'], input='env', env=currenv, \n                                    stderr=subprocess.PIPE,\n                                    universal_newlines=True)\n    except subprocess.CalledProcessError:\n        s = ''\n    items = [line.split('=', 1) for line in s.splitlines() if '=' in line]\n    env = dict(items)\n    return env\n\ndef xonshrc_context(rcfile=None, execer=None):\n    \"\"\"Attempts to read in xonshrc file, and return the contents.\"\"\"\n    if rcfile is None or execer is None or not os.path.isfile(rcfile):\n        return {}\n    with open(rcfile, 'r') as f:\n        rc = f.read()\n    if not rc.endswith('\\n'):\n        rc += '\\n'\n    fname = execer.filename\n    env = {}\n    try:\n        execer.filename = rcfile\n        execer.exec(rc, glbs={}, locs=env)\n    except SyntaxError as err:\n        msg = 'syntax error in xonsh run control file {0!r}: {1!s}'\n        warn(msg.format(rcfile, err), RuntimeWarning)\n    finally:\n        execer.filename = fname\n    return env\n\ndef default_env(env=None):\n    \"\"\"Constructs a default xonsh environment.\"\"\"\n    # in order of increasing precedence\n    ctx = dict(BASE_ENV)\n    ctx.update(os.environ)\n    ctx.update(bash_env())\n    if env is not None:\n        ctx.update(env)\n    return ctx\n", "path": "xonsh/environ.py"}], "after_files": [{"content": "\"\"\"Environment for the xonsh shell.\n\"\"\"\nimport os\nimport re\nimport socket\nimport locale\nimport builtins\nimport platform\nimport subprocess\nfrom warnings import warn\n\nfrom xonsh.tools import TERM_COLORS\n\ndef current_branch(cwd=None):\n    \"\"\"Gets the branch for a current working directory. Returns None\n    if the cwd is not a repository.  This currently only works for git, \n    bust should be extended in the future.\n    \"\"\"\n    branch = None\n    cwd = os.getcwd() if cwd is None else cwd\n\n    # step out completely if git is not installed\n    try:\n        binary_location = subprocess.check_output(['which', 'git'], cwd=cwd,\n                                    stderr=subprocess.PIPE,\n                                    universal_newlines=True)\n        if not binary_location:\n            return branch\n    except subprocess.CalledProcessError:\n        return branch\n\n    prompt_scripts = [\n        '/usr/lib/git-core/git-sh-prompt',\n        '/usr/local/etc/bash_completion.d/git-prompt.sh'\n    ]\n\n    for script in prompt_scripts:\n        # note that this is about 10x faster than bash -i \"__git_ps1\"\n        _input = ('source {}; __git_ps1 \"${{1:-%s}}\"'.format(script))\n        try:\n            branch = subprocess.check_output(['bash',], cwd=cwd, input=_input,\n                                        stderr=subprocess.PIPE,\n                                        universal_newlines=True) or None\n        except subprocess.CalledProcessError:\n            continue\n\n    # fall back to using the git binary if the above failed\n    if branch is None:\n        try:\n            s = subprocess.check_output(['git', 'rev-parse','--abbrev-ref', 'HEAD'],\n                    stderr=subprocess.PIPE, cwd=cwd,\n                    universal_newlines=True) \n            s = s.strip()\n            if len(s) > 0:\n                branch = s\n        except subprocess.CalledProcessError:\n            pass\n\n    return branch\n\n\ndefault_prompt = ('{BOLD_GREEN}{user}@{hostname}{BOLD_BLUE} '\n                  '{cwd}{BOLD_RED}{curr_branch} {BOLD_BLUE}${NO_COLOR} ')\ndefault_title = '{user}@{hostname}: {cwd} | xonsh'\n\ndef format_prompt(template=default_prompt):\n    \"\"\"Formats a xonsh prompt template string.\n\n    The following keyword arguments are recognized in the template string:\n\n    + user -- Name of current user\n    + hostname -- Name of host computer\n    + cwd -- Current working directory\n    + curr_branch -- Name of current git branch (preceded by a space), if any\n    + (QUALIFIER\\_)COLORNAME -- Inserts an ANSI color code\n        - COLORNAME can be any of:\n              BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE\n        - QUALIFIER is optional and can be any of:\n              BOLD, UNDERLINE, BACKGROUND, INTENSE,\n              BOLD_INTENSE, BACKGROUND_INTENSE\n    + NO_COLOR -- Resets any previously used color codes\n    \"\"\"\n    env = builtins.__xonsh_env__\n    cwd = env['PWD']\n    branch = current_branch(cwd=cwd)\n    branch = '' if branch is None else ' ' + branch\n    p = template.format(\n            user=env.get('USER', '<user>'),\n            hostname=socket.gethostname(),\n            cwd=cwd.replace(env['HOME'], '~'),\n            curr_branch=branch,\n            **TERM_COLORS\n            )\n    return p\n\n\nRE_HIDDEN = re.compile('\\001.*?\\002')\n\ndef multiline_prompt():\n    \"\"\"Returns the filler text for the prompt in multiline scenarios.\"\"\"\n    curr = builtins.__xonsh_env__.get('PROMPT', \"set '$PROMPT = ...' $ \")\n    curr = curr() if callable(curr) else curr\n    curr = format_prompt(curr)\n    line = curr.rsplit('\\n', 1)[1] if '\\n' in curr else curr\n    line = RE_HIDDEN.sub('', line)  # gets rid of colors\n    # most prompts end in whitespace, head is the part before that.\n    head = line.rstrip()\n    headlen = len(head)\n    # tail is the trailing whitespace\n    tail = line if headlen == 0 else line.rsplit(head[-1], 1)[1]\n    # now to constuct the actual string\n    dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT', '.')\n    dots = dots() if callable(dots) else dots\n    if dots is None or len(dots) == 0:\n        return ''\n    return (dots*(headlen//len(dots))) + dots[:headlen%len(dots)] + tail\n\n\nBASE_ENV = {\n    'INDENT': '    ',\n    'PROMPT': default_prompt,\n    'TITLE': default_title,\n    'MULTILINE_PROMPT': '.',\n    'XONSHRC': os.path.expanduser('~/.xonshrc'),\n    'XONSH_HISTORY_SIZE': 8128,\n    'XONSH_HISTORY_FILE': os.path.expanduser('~/.xonsh_history'),\n    'LC_CTYPE': locale.setlocale(locale.LC_CTYPE),\n    'LC_COLLATE': locale.setlocale(locale.LC_COLLATE),\n    'LC_TIME': locale.setlocale(locale.LC_TIME),\n    'LC_MONETARY': locale.setlocale(locale.LC_MONETARY),\n    'LC_MESSAGES': locale.setlocale(locale.LC_MESSAGES),\n    'LC_NUMERIC': locale.setlocale(locale.LC_NUMERIC),\n    }\n\nif platform.system() == 'Darwin':\n    BASE_ENV['BASH_COMPLETIONS'] = []\nelse:\n    BASE_ENV['BASH_COMPLETIONS'] = ['/etc/bash_completion', \n                                    '/usr/share/bash-completion/completions/git']\n\ndef bash_env():\n    \"\"\"Attempts to compute the bash envinronment variables.\"\"\"\n    currenv = None\n    if hasattr(builtins, '__xonsh_env__'):\n        currenv = builtins.__xonsh_env__.detype()\n    try:\n        s = subprocess.check_output(['bash', '-i'], input='env', env=currenv, \n                                    stderr=subprocess.PIPE,\n                                    universal_newlines=True)\n    except subprocess.CalledProcessError:\n        s = ''\n    items = [line.split('=', 1) for line in s.splitlines() if '=' in line]\n    env = dict(items)\n    return env\n\ndef xonshrc_context(rcfile=None, execer=None):\n    \"\"\"Attempts to read in xonshrc file, and return the contents.\"\"\"\n    if rcfile is None or execer is None or not os.path.isfile(rcfile):\n        return {}\n    with open(rcfile, 'r') as f:\n        rc = f.read()\n    if not rc.endswith('\\n'):\n        rc += '\\n'\n    fname = execer.filename\n    env = {}\n    try:\n        execer.filename = rcfile\n        execer.exec(rc, glbs=env)\n    except SyntaxError as err:\n        msg = 'syntax error in xonsh run control file {0!r}: {1!s}'\n        warn(msg.format(rcfile, err), RuntimeWarning)\n    finally:\n        execer.filename = fname\n    return env\n\ndef default_env(env=None):\n    \"\"\"Constructs a default xonsh environment.\"\"\"\n    # in order of increasing precedence\n    ctx = dict(BASE_ENV)\n    ctx.update(os.environ)\n    ctx.update(bash_env())\n    if env is not None:\n        ctx.update(env)\n    return ctx\n", "path": "xonsh/environ.py"}]}