We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
CTRL-C during config wizard results in loss of input to terminal
Running bash in a Terminator window, when I first started xonsh, I was asked if I wanted to run the config wizard.  I chose yes, but then eventually decided I didn't want to finish, so I hit CTRL-C.  This eventually got me back to bash, but when I pressed keys, the keys didn't show up in the terminal windows.  I had to close the window and open a new one.


--- 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/main.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """The main xonsh script."""
3 import os
4 import sys
5 import enum
6 import builtins
7 from argparse import ArgumentParser, ArgumentTypeError
8 from contextlib import contextmanager
9 
10 try:
11     from setproctitle import setproctitle
12 except ImportError:
13     setproctitle = None
14 
15 from xonsh import __version__
16 from xonsh.shell import Shell
17 from xonsh.pretty import pprint, pretty
18 from xonsh.proc import HiddenCompletedCommand
19 from xonsh.jobs import ignore_sigtstp
20 from xonsh.tools import HAVE_PYGMENTS, setup_win_unicode_console, print_color, ON_WINDOWS
21 
22 if HAVE_PYGMENTS:
23     import pygments
24     from xonsh import pyghooks
25 
26 
27 def path_argument(s):
28     """Return a path only if the path is actually legal
29 
30     This is very similar to argparse.FileType, except that it doesn't return
31     an open file handle, but rather simply validates the path."""
32 
33     s = os.path.abspath(os.path.expanduser(s))
34     if not os.path.isfile(s):
35         raise ArgumentTypeError('"%s" must be a valid path to a file' % s)
36     return s
37 
38 
39 parser = ArgumentParser(description='xonsh', add_help=False)
40 parser.add_argument('-h', '--help',
41                     dest='help',
42                     action='store_true',
43                     default=False,
44                     help='show help and exit')
45 parser.add_argument('-V', '--version',
46                     dest='version',
47                     action='store_true',
48                     default=False,
49                     help='show version information and exit')
50 parser.add_argument('-c',
51                     help="Run a single command and exit",
52                     dest='command',
53                     required=False,
54                     default=None)
55 parser.add_argument('-i', '--interactive',
56                     help='force running in interactive mode',
57                     dest='force_interactive',
58                     action='store_true',
59                     default=False)
60 parser.add_argument('-l', '--login',
61                     help='run as a login shell',
62                     dest='login',
63                     action='store_true',
64                     default=False)
65 parser.add_argument('--config-path',
66                     help='specify a custom static configuration file',
67                     dest='config_path',
68                     default=None,
69                     type=path_argument)
70 parser.add_argument('--no-rc',
71                     help="Do not load the .xonshrc files",
72                     dest='norc',
73                     action='store_true',
74                     default=False)
75 parser.add_argument('-D',
76                     dest='defines',
77                     help='define an environment variable, in the form of '
78                          '-DNAME=VAL. May be used many times.',
79                     metavar='ITEM',
80                     nargs='*',
81                     default=None)
82 parser.add_argument('--shell-type',
83                     help='What kind of shell should be used. '
84                          'Possible options: readline, prompt_toolkit, random. '
85                          'Warning! If set this overrides $SHELL_TYPE variable.',
86                     dest='shell_type',
87                     choices=('readline', 'prompt_toolkit', 'best', 'random'),
88                     default=None)
89 parser.add_argument('file',
90                     metavar='script-file',
91                     help='If present, execute the script in script-file'
92                          ' and exit',
93                     nargs='?',
94                     default=None)
95 parser.add_argument('args',
96                     metavar='args',
97                     help='Additional arguments to the script specified '
98                          'by script-file',
99                     nargs='*',
100                     default=[])
101 
102 
103 def arg_undoers():
104     au = {
105         '-h': (lambda args: setattr(args, 'help', False)),
106         '-V': (lambda args: setattr(args, 'version', False)),
107         '-c': (lambda args: setattr(args, 'command', None)),
108         '-i': (lambda args: setattr(args, 'force_interactive', False)),
109         '-l': (lambda args: setattr(args, 'login', False)),
110         '-c': (lambda args: setattr(args, 'command', None)),
111         '--config-path': (lambda args: delattr(args, 'config_path')),
112         '--no-rc': (lambda args: setattr(args, 'norc', False)),
113         '-D': (lambda args: setattr(args, 'defines', None)),
114         '--shell-type': (lambda args: setattr(args, 'shell_type', None)),
115         }
116     au['--help'] = au['-h']
117     au['--version'] = au['-V']
118     au['--interactive'] = au['-i']
119     au['--login'] = au['-l']
120 
121     return au
122 
123 def undo_args(args):
124     """Undoes missaligned args."""
125     au = arg_undoers()
126     for a in args.args:
127         if a in au:
128             au[a](args)
129         else:
130             for k in au:
131                 if a.startswith(k):
132                     au[k](args)
133 
134 def _pprint_displayhook(value):
135     if value is None or isinstance(value, HiddenCompletedCommand):
136         return
137     builtins._ = None  # Set '_' to None to avoid recursion
138     if HAVE_PYGMENTS:
139         s = pretty(value)  # color case
140         lexer = pyghooks.XonshLexer()
141         tokens = list(pygments.lex(s, lexer=lexer))
142         print_color(tokens)
143     else:
144         pprint(value)  # black & white case
145     builtins._ = value
146 
147 class XonshMode(enum.Enum):
148     single_command = 0
149     script_from_file = 1
150     script_from_stdin = 2
151     interactive = 3
152 
153 def premain(argv=None):
154     """Setup for main xonsh entry point, returns parsed arguments."""
155     if setproctitle is not None:
156         setproctitle(' '.join(['xonsh'] + sys.argv[1:]))
157     args, other = parser.parse_known_args(argv)
158     if args.file is not None:
159         real_argv = (argv or sys.argv)
160         i = real_argv.index(args.file)
161         args.args = real_argv[i+1:]
162         undo_args(args)
163     if args.help:
164         parser.print_help()
165         exit()
166     if args.version:
167         version = '/'.join(('xonsh', __version__)),
168         print(version)
169         exit()
170     shell_kwargs = {'shell_type': args.shell_type,
171                     'completer': False,
172                     'login': False}
173     if args.login:
174         shell_kwargs['login'] = True
175     if args.config_path is None:
176         shell_kwargs['config'] = args.config_path
177     if args.norc:
178         shell_kwargs['rc'] = ()
179     setattr(sys, 'displayhook', _pprint_displayhook)
180     if args.command is not None:
181         args.mode = XonshMode.single_command
182         shell_kwargs['shell_type'] = 'none'
183     elif args.file is not None:
184         args.mode = XonshMode.script_from_file
185         shell_kwargs['shell_type'] = 'none'
186     elif not sys.stdin.isatty() and not args.force_interactive:
187         args.mode = XonshMode.script_from_stdin
188         shell_kwargs['shell_type'] = 'none'
189     else:
190         args.mode = XonshMode.interactive
191         shell_kwargs['completer'] = True
192         shell_kwargs['login'] = True
193     shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
194     from xonsh import imphooks
195     env = builtins.__xonsh_env__
196     env['XONSH_LOGIN'] = shell_kwargs['login']
197     if args.defines is not None:
198         env.update([x.split('=', 1) for x in args.defines])
199     env['XONSH_INTERACTIVE'] = False
200     if ON_WINDOWS:
201         setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))
202     return args
203 
204 
205 def main(argv=None):
206     """Main entry point for xonsh cli."""
207     args = premain(argv)
208     env = builtins.__xonsh_env__
209     shell = builtins.__xonsh_shell__
210     if args.mode == XonshMode.single_command:
211         # run a single command and exit
212         shell.default(args.command)
213     elif args.mode == XonshMode.script_from_file:
214         # run a script contained in a file
215         if os.path.isfile(args.file):
216             with open(args.file) as f:
217                 code = f.read()
218             code = code if code.endswith('\n') else code + '\n'
219             sys.argv = args.args
220             env['ARGS'] = [args.file] + args.args
221             code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,
222                                         filename=args.file)
223             shell.execer.exec(code, mode='exec', glbs=shell.ctx)
224         else:
225             print('xonsh: {0}: No such file or directory.'.format(args.file))
226     elif args.mode == XonshMode.script_from_stdin:
227         # run a script given on stdin
228         code = sys.stdin.read()
229         code = code if code.endswith('\n') else code + '\n'
230         code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,
231                                     filename='<stdin>')
232         shell.execer.exec(code, mode='exec', glbs=shell.ctx)
233     else:
234         # otherwise, enter the shell
235         env['XONSH_INTERACTIVE'] = True
236         ignore_sigtstp()
237         if not env['LOADED_CONFIG'] and not any(env['LOADED_RC_FILES']):
238             print('Could not find xonsh configuration or run control files.')
239             code = '$[xonfig wizard --confirm]'
240             shell.execer.exec(code, mode='single', glbs=shell.ctx)
241         shell.cmdloop()
242     postmain(args)
243 
244 
245 def postmain(args=None):
246     """Teardown for main xonsh entry point, accepts parsed arguments."""
247     if ON_WINDOWS:
248         setup_win_unicode_console(enable=False)
249     del builtins.__xonsh_shell__
250 
251 
252 @contextmanager
253 def main_context(argv=None):
254     """Generator that runs pre- and post-main() functions. This has two iterations.
255     The first yields the shell. The second returns None but cleans
256     up the shell.
257     """
258     args = premain(argv)
259     yield builtins.__xonsh_shell__
260     postmain(args)
261 
262 
263 
264 if __name__ == '__main__':
265     main()
266
```
--- 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/main.py b/xonsh/main.py
--- a/xonsh/main.py
+++ b/xonsh/main.py
@@ -236,8 +236,8 @@
         ignore_sigtstp()
         if not env['LOADED_CONFIG'] and not any(env['LOADED_RC_FILES']):
             print('Could not find xonsh configuration or run control files.')
-            code = '$[xonfig wizard --confirm]'
-            shell.execer.exec(code, mode='single', glbs=shell.ctx)
+            from xonsh import xonfig  # lazy import
+            xonfig.main(['wizard', '--confirm'])
         shell.cmdloop()
     postmain(args)

{"golden_diff": "diff --git a/xonsh/main.py b/xonsh/main.py\n--- a/xonsh/main.py\n+++ b/xonsh/main.py\n@@ -236,8 +236,8 @@\n         ignore_sigtstp()\n         if not env['LOADED_CONFIG'] and not any(env['LOADED_RC_FILES']):\n             print('Could not find xonsh configuration or run control files.')\n-            code = '$[xonfig wizard --confirm]'\n-            shell.execer.exec(code, mode='single', glbs=shell.ctx)\n+            from xonsh import xonfig  # lazy import\n+            xonfig.main(['wizard', '--confirm'])\n         shell.cmdloop()\n     postmain(args)\n", "issue": "CTRL-C during config wizard results in loss of input to terminal\nRunning bash in a Terminator window, when I first started xonsh, I was asked if I wanted to run the config wizard.  I chose yes, but then eventually decided I didn't want to finish, so I hit CTRL-C.  This eventually got me back to bash, but when I pressed keys, the keys didn't show up in the terminal windows.  I had to close the window and open a new one.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The main xonsh script.\"\"\"\nimport os\nimport sys\nimport enum\nimport builtins\nfrom argparse import ArgumentParser, ArgumentTypeError\nfrom contextlib import contextmanager\n\ntry:\n    from setproctitle import setproctitle\nexcept ImportError:\n    setproctitle = None\n\nfrom xonsh import __version__\nfrom xonsh.shell import Shell\nfrom xonsh.pretty import pprint, pretty\nfrom xonsh.proc import HiddenCompletedCommand\nfrom xonsh.jobs import ignore_sigtstp\nfrom xonsh.tools import HAVE_PYGMENTS, setup_win_unicode_console, print_color, ON_WINDOWS\n\nif HAVE_PYGMENTS:\n    import pygments\n    from xonsh import pyghooks\n\n\ndef path_argument(s):\n    \"\"\"Return a path only if the path is actually legal\n\n    This is very similar to argparse.FileType, except that it doesn't return\n    an open file handle, but rather simply validates the path.\"\"\"\n\n    s = os.path.abspath(os.path.expanduser(s))\n    if not os.path.isfile(s):\n        raise ArgumentTypeError('\"%s\" must be a valid path to a file' % s)\n    return s\n\n\nparser = ArgumentParser(description='xonsh', add_help=False)\nparser.add_argument('-h', '--help',\n                    dest='help',\n                    action='store_true',\n                    default=False,\n                    help='show help and exit')\nparser.add_argument('-V', '--version',\n                    dest='version',\n                    action='store_true',\n                    default=False,\n                    help='show version information and exit')\nparser.add_argument('-c',\n                    help=\"Run a single command and exit\",\n                    dest='command',\n                    required=False,\n                    default=None)\nparser.add_argument('-i', '--interactive',\n                    help='force running in interactive mode',\n                    dest='force_interactive',\n                    action='store_true',\n                    default=False)\nparser.add_argument('-l', '--login',\n                    help='run as a login shell',\n                    dest='login',\n                    action='store_true',\n                    default=False)\nparser.add_argument('--config-path',\n                    help='specify a custom static configuration file',\n                    dest='config_path',\n                    default=None,\n                    type=path_argument)\nparser.add_argument('--no-rc',\n                    help=\"Do not load the .xonshrc files\",\n                    dest='norc',\n                    action='store_true',\n                    default=False)\nparser.add_argument('-D',\n                    dest='defines',\n                    help='define an environment variable, in the form of '\n                         '-DNAME=VAL. May be used many times.',\n                    metavar='ITEM',\n                    nargs='*',\n                    default=None)\nparser.add_argument('--shell-type',\n                    help='What kind of shell should be used. '\n                         'Possible options: readline, prompt_toolkit, random. '\n                         'Warning! If set this overrides $SHELL_TYPE variable.',\n                    dest='shell_type',\n                    choices=('readline', 'prompt_toolkit', 'best', 'random'),\n                    default=None)\nparser.add_argument('file',\n                    metavar='script-file',\n                    help='If present, execute the script in script-file'\n                         ' and exit',\n                    nargs='?',\n                    default=None)\nparser.add_argument('args',\n                    metavar='args',\n                    help='Additional arguments to the script specified '\n                         'by script-file',\n                    nargs='*',\n                    default=[])\n\n\ndef arg_undoers():\n    au = {\n        '-h': (lambda args: setattr(args, 'help', False)),\n        '-V': (lambda args: setattr(args, 'version', False)),\n        '-c': (lambda args: setattr(args, 'command', None)),\n        '-i': (lambda args: setattr(args, 'force_interactive', False)),\n        '-l': (lambda args: setattr(args, 'login', False)),\n        '-c': (lambda args: setattr(args, 'command', None)),\n        '--config-path': (lambda args: delattr(args, 'config_path')),\n        '--no-rc': (lambda args: setattr(args, 'norc', False)),\n        '-D': (lambda args: setattr(args, 'defines', None)),\n        '--shell-type': (lambda args: setattr(args, 'shell_type', None)),\n        }\n    au['--help'] = au['-h']\n    au['--version'] = au['-V']\n    au['--interactive'] = au['-i']\n    au['--login'] = au['-l']\n\n    return au\n\ndef undo_args(args):\n    \"\"\"Undoes missaligned args.\"\"\"\n    au = arg_undoers()\n    for a in args.args:\n        if a in au:\n            au[a](args)\n        else:\n            for k in au:\n                if a.startswith(k):\n                    au[k](args)\n\ndef _pprint_displayhook(value):\n    if value is None or isinstance(value, HiddenCompletedCommand):\n        return\n    builtins._ = None  # Set '_' to None to avoid recursion\n    if HAVE_PYGMENTS:\n        s = pretty(value)  # color case\n        lexer = pyghooks.XonshLexer()\n        tokens = list(pygments.lex(s, lexer=lexer))\n        print_color(tokens)\n    else:\n        pprint(value)  # black & white case\n    builtins._ = value\n\nclass XonshMode(enum.Enum):\n    single_command = 0\n    script_from_file = 1\n    script_from_stdin = 2\n    interactive = 3\n\ndef premain(argv=None):\n    \"\"\"Setup for main xonsh entry point, returns parsed arguments.\"\"\"\n    if setproctitle is not None:\n        setproctitle(' '.join(['xonsh'] + sys.argv[1:]))\n    args, other = parser.parse_known_args(argv)\n    if args.file is not None:\n        real_argv = (argv or sys.argv)\n        i = real_argv.index(args.file)\n        args.args = real_argv[i+1:]\n        undo_args(args)\n    if args.help:\n        parser.print_help()\n        exit()\n    if args.version:\n        version = '/'.join(('xonsh', __version__)),\n        print(version)\n        exit()\n    shell_kwargs = {'shell_type': args.shell_type,\n                    'completer': False,\n                    'login': False}\n    if args.login:\n        shell_kwargs['login'] = True\n    if args.config_path is None:\n        shell_kwargs['config'] = args.config_path\n    if args.norc:\n        shell_kwargs['rc'] = ()\n    setattr(sys, 'displayhook', _pprint_displayhook)\n    if args.command is not None:\n        args.mode = XonshMode.single_command\n        shell_kwargs['shell_type'] = 'none'\n    elif args.file is not None:\n        args.mode = XonshMode.script_from_file\n        shell_kwargs['shell_type'] = 'none'\n    elif not sys.stdin.isatty() and not args.force_interactive:\n        args.mode = XonshMode.script_from_stdin\n        shell_kwargs['shell_type'] = 'none'\n    else:\n        args.mode = XonshMode.interactive\n        shell_kwargs['completer'] = True\n        shell_kwargs['login'] = True\n    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)\n    from xonsh import imphooks\n    env = builtins.__xonsh_env__\n    env['XONSH_LOGIN'] = shell_kwargs['login']\n    if args.defines is not None:\n        env.update([x.split('=', 1) for x in args.defines])\n    env['XONSH_INTERACTIVE'] = False\n    if ON_WINDOWS:\n        setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))\n    return args\n\n\ndef main(argv=None):\n    \"\"\"Main entry point for xonsh cli.\"\"\"\n    args = premain(argv)\n    env = builtins.__xonsh_env__\n    shell = builtins.__xonsh_shell__\n    if args.mode == XonshMode.single_command:\n        # run a single command and exit\n        shell.default(args.command)\n    elif args.mode == XonshMode.script_from_file:\n        # run a script contained in a file\n        if os.path.isfile(args.file):\n            with open(args.file) as f:\n                code = f.read()\n            code = code if code.endswith('\\n') else code + '\\n'\n            sys.argv = args.args\n            env['ARGS'] = [args.file] + args.args\n            code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,\n                                        filename=args.file)\n            shell.execer.exec(code, mode='exec', glbs=shell.ctx)\n        else:\n            print('xonsh: {0}: No such file or directory.'.format(args.file))\n    elif args.mode == XonshMode.script_from_stdin:\n        # run a script given on stdin\n        code = sys.stdin.read()\n        code = code if code.endswith('\\n') else code + '\\n'\n        code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,\n                                    filename='<stdin>')\n        shell.execer.exec(code, mode='exec', glbs=shell.ctx)\n    else:\n        # otherwise, enter the shell\n        env['XONSH_INTERACTIVE'] = True\n        ignore_sigtstp()\n        if not env['LOADED_CONFIG'] and not any(env['LOADED_RC_FILES']):\n            print('Could not find xonsh configuration or run control files.')\n            code = '$[xonfig wizard --confirm]'\n            shell.execer.exec(code, mode='single', glbs=shell.ctx)\n        shell.cmdloop()\n    postmain(args)\n\n\ndef postmain(args=None):\n    \"\"\"Teardown for main xonsh entry point, accepts parsed arguments.\"\"\"\n    if ON_WINDOWS:\n        setup_win_unicode_console(enable=False)\n    del builtins.__xonsh_shell__\n\n\n@contextmanager\ndef main_context(argv=None):\n    \"\"\"Generator that runs pre- and post-main() functions. This has two iterations.\n    The first yields the shell. The second returns None but cleans\n    up the shell.\n    \"\"\"\n    args = premain(argv)\n    yield builtins.__xonsh_shell__\n    postmain(args)\n\n\n\nif __name__ == '__main__':\n    main()\n", "path": "xonsh/main.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The main xonsh script.\"\"\"\nimport os\nimport sys\nimport enum\nimport builtins\nfrom argparse import ArgumentParser, ArgumentTypeError\nfrom contextlib import contextmanager\n\ntry:\n    from setproctitle import setproctitle\nexcept ImportError:\n    setproctitle = None\n\nfrom xonsh import __version__\nfrom xonsh.shell import Shell\nfrom xonsh.pretty import pprint, pretty\nfrom xonsh.proc import HiddenCompletedCommand\nfrom xonsh.jobs import ignore_sigtstp\nfrom xonsh.tools import HAVE_PYGMENTS, setup_win_unicode_console, print_color, ON_WINDOWS\n\nif HAVE_PYGMENTS:\n    import pygments\n    from xonsh import pyghooks\n\n\ndef path_argument(s):\n    \"\"\"Return a path only if the path is actually legal\n\n    This is very similar to argparse.FileType, except that it doesn't return\n    an open file handle, but rather simply validates the path.\"\"\"\n\n    s = os.path.abspath(os.path.expanduser(s))\n    if not os.path.isfile(s):\n        raise ArgumentTypeError('\"%s\" must be a valid path to a file' % s)\n    return s\n\n\nparser = ArgumentParser(description='xonsh', add_help=False)\nparser.add_argument('-h', '--help',\n                    dest='help',\n                    action='store_true',\n                    default=False,\n                    help='show help and exit')\nparser.add_argument('-V', '--version',\n                    dest='version',\n                    action='store_true',\n                    default=False,\n                    help='show version information and exit')\nparser.add_argument('-c',\n                    help=\"Run a single command and exit\",\n                    dest='command',\n                    required=False,\n                    default=None)\nparser.add_argument('-i', '--interactive',\n                    help='force running in interactive mode',\n                    dest='force_interactive',\n                    action='store_true',\n                    default=False)\nparser.add_argument('-l', '--login',\n                    help='run as a login shell',\n                    dest='login',\n                    action='store_true',\n                    default=False)\nparser.add_argument('--config-path',\n                    help='specify a custom static configuration file',\n                    dest='config_path',\n                    default=None,\n                    type=path_argument)\nparser.add_argument('--no-rc',\n                    help=\"Do not load the .xonshrc files\",\n                    dest='norc',\n                    action='store_true',\n                    default=False)\nparser.add_argument('-D',\n                    dest='defines',\n                    help='define an environment variable, in the form of '\n                         '-DNAME=VAL. May be used many times.',\n                    metavar='ITEM',\n                    nargs='*',\n                    default=None)\nparser.add_argument('--shell-type',\n                    help='What kind of shell should be used. '\n                         'Possible options: readline, prompt_toolkit, random. '\n                         'Warning! If set this overrides $SHELL_TYPE variable.',\n                    dest='shell_type',\n                    choices=('readline', 'prompt_toolkit', 'best', 'random'),\n                    default=None)\nparser.add_argument('file',\n                    metavar='script-file',\n                    help='If present, execute the script in script-file'\n                         ' and exit',\n                    nargs='?',\n                    default=None)\nparser.add_argument('args',\n                    metavar='args',\n                    help='Additional arguments to the script specified '\n                         'by script-file',\n                    nargs='*',\n                    default=[])\n\n\ndef arg_undoers():\n    au = {\n        '-h': (lambda args: setattr(args, 'help', False)),\n        '-V': (lambda args: setattr(args, 'version', False)),\n        '-c': (lambda args: setattr(args, 'command', None)),\n        '-i': (lambda args: setattr(args, 'force_interactive', False)),\n        '-l': (lambda args: setattr(args, 'login', False)),\n        '-c': (lambda args: setattr(args, 'command', None)),\n        '--config-path': (lambda args: delattr(args, 'config_path')),\n        '--no-rc': (lambda args: setattr(args, 'norc', False)),\n        '-D': (lambda args: setattr(args, 'defines', None)),\n        '--shell-type': (lambda args: setattr(args, 'shell_type', None)),\n        }\n    au['--help'] = au['-h']\n    au['--version'] = au['-V']\n    au['--interactive'] = au['-i']\n    au['--login'] = au['-l']\n\n    return au\n\ndef undo_args(args):\n    \"\"\"Undoes missaligned args.\"\"\"\n    au = arg_undoers()\n    for a in args.args:\n        if a in au:\n            au[a](args)\n        else:\n            for k in au:\n                if a.startswith(k):\n                    au[k](args)\n\ndef _pprint_displayhook(value):\n    if value is None or isinstance(value, HiddenCompletedCommand):\n        return\n    builtins._ = None  # Set '_' to None to avoid recursion\n    if HAVE_PYGMENTS:\n        s = pretty(value)  # color case\n        lexer = pyghooks.XonshLexer()\n        tokens = list(pygments.lex(s, lexer=lexer))\n        print_color(tokens)\n    else:\n        pprint(value)  # black & white case\n    builtins._ = value\n\nclass XonshMode(enum.Enum):\n    single_command = 0\n    script_from_file = 1\n    script_from_stdin = 2\n    interactive = 3\n\ndef premain(argv=None):\n    \"\"\"Setup for main xonsh entry point, returns parsed arguments.\"\"\"\n    if setproctitle is not None:\n        setproctitle(' '.join(['xonsh'] + sys.argv[1:]))\n    args, other = parser.parse_known_args(argv)\n    if args.file is not None:\n        real_argv = (argv or sys.argv)\n        i = real_argv.index(args.file)\n        args.args = real_argv[i+1:]\n        undo_args(args)\n    if args.help:\n        parser.print_help()\n        exit()\n    if args.version:\n        version = '/'.join(('xonsh', __version__)),\n        print(version)\n        exit()\n    shell_kwargs = {'shell_type': args.shell_type,\n                    'completer': False,\n                    'login': False}\n    if args.login:\n        shell_kwargs['login'] = True\n    if args.config_path is None:\n        shell_kwargs['config'] = args.config_path\n    if args.norc:\n        shell_kwargs['rc'] = ()\n    setattr(sys, 'displayhook', _pprint_displayhook)\n    if args.command is not None:\n        args.mode = XonshMode.single_command\n        shell_kwargs['shell_type'] = 'none'\n    elif args.file is not None:\n        args.mode = XonshMode.script_from_file\n        shell_kwargs['shell_type'] = 'none'\n    elif not sys.stdin.isatty() and not args.force_interactive:\n        args.mode = XonshMode.script_from_stdin\n        shell_kwargs['shell_type'] = 'none'\n    else:\n        args.mode = XonshMode.interactive\n        shell_kwargs['completer'] = True\n        shell_kwargs['login'] = True\n    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)\n    from xonsh import imphooks\n    env = builtins.__xonsh_env__\n    env['XONSH_LOGIN'] = shell_kwargs['login']\n    if args.defines is not None:\n        env.update([x.split('=', 1) for x in args.defines])\n    env['XONSH_INTERACTIVE'] = False\n    if ON_WINDOWS:\n        setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))\n    return args\n\n\ndef main(argv=None):\n    \"\"\"Main entry point for xonsh cli.\"\"\"\n    args = premain(argv)\n    env = builtins.__xonsh_env__\n    shell = builtins.__xonsh_shell__\n    if args.mode == XonshMode.single_command:\n        # run a single command and exit\n        shell.default(args.command)\n    elif args.mode == XonshMode.script_from_file:\n        # run a script contained in a file\n        if os.path.isfile(args.file):\n            with open(args.file) as f:\n                code = f.read()\n            code = code if code.endswith('\\n') else code + '\\n'\n            sys.argv = args.args\n            env['ARGS'] = [args.file] + args.args\n            code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,\n                                        filename=args.file)\n            shell.execer.exec(code, mode='exec', glbs=shell.ctx)\n        else:\n            print('xonsh: {0}: No such file or directory.'.format(args.file))\n    elif args.mode == XonshMode.script_from_stdin:\n        # run a script given on stdin\n        code = sys.stdin.read()\n        code = code if code.endswith('\\n') else code + '\\n'\n        code = shell.execer.compile(code, mode='exec', glbs=shell.ctx,\n                                    filename='<stdin>')\n        shell.execer.exec(code, mode='exec', glbs=shell.ctx)\n    else:\n        # otherwise, enter the shell\n        env['XONSH_INTERACTIVE'] = True\n        ignore_sigtstp()\n        if not env['LOADED_CONFIG'] and not any(env['LOADED_RC_FILES']):\n            print('Could not find xonsh configuration or run control files.')\n            from xonsh import xonfig  # lazy import\n            xonfig.main(['wizard', '--confirm'])\n        shell.cmdloop()\n    postmain(args)\n\n\ndef postmain(args=None):\n    \"\"\"Teardown for main xonsh entry point, accepts parsed arguments.\"\"\"\n    if ON_WINDOWS:\n        setup_win_unicode_console(enable=False)\n    del builtins.__xonsh_shell__\n\n\n@contextmanager\ndef main_context(argv=None):\n    \"\"\"Generator that runs pre- and post-main() functions. This has two iterations.\n    The first yields the shell. The second returns None but cleans\n    up the shell.\n    \"\"\"\n    args = premain(argv)\n    yield builtins.__xonsh_shell__\n    postmain(args)\n\n\n\nif __name__ == '__main__':\n    main()\n", "path": "xonsh/main.py"}]}