We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Invalid sys.argv when running a xonsh script
``` sh
$ cat test.py
#!/usr/bin/env python3
import sys
print(sys.argv)
$ ./test.py --hello world
['./test.py', '--hello', 'world']
$ python3 test.py --hello world
['test.py', '--hello', 'world']
$ sed -i s/python3/xonsh/ test.py
$ ./test.py --hello world
['--hello', 'world']
$ xonsh test.py --hello world
['--hello', 'world']
$ execx($(cat test.py))
['/usr/local/bin/xonsh']
$
```

As you can see, program name is not passed into `argv[0]`. This behaviour differs from _every other_ existing programming language, including Python. Thus, none of the option parsing libraries work with default settings, since they try to use `sys.argv[1:]`.
Hoping this is a bug that's going to be fixed, I'm using the following workaround for now:

``` py
if semver.match(re.search(r"([\w.-]+)\W*$", $(xonsh --version)).group(1), "<=0.4.4"):
    args = sys.argv
else:
    args = sys.argv[1:]
```

By the way, why does `xonsh --version` print a `repr` of a tuple?


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

{"golden_diff": "diff --git a/xonsh/main.py b/xonsh/main.py\n--- a/xonsh/main.py\n+++ b/xonsh/main.py\n@@ -159,7 +159,7 @@\n         parser.print_help()\n         parser.exit()\n     if args.version:\n-        version = '/'.join(('xonsh', __version__)),\n+        version = '/'.join(('xonsh', __version__))\n         print(version)\n         parser.exit()\n     shell_kwargs = {'shell_type': args.shell_type,\n@@ -224,8 +224,8 @@\n         # run a script contained in a file\n         path = os.path.abspath(os.path.expanduser(args.file))\n         if os.path.isfile(path):\n-            sys.argv = args.args\n-            env['ARGS'] = [args.file] + args.args\n+            sys.argv = [args.file] + args.args\n+            env['ARGS'] = sys.argv[:]  # $ARGS is not sys.argv\n             env['XONSH_SOURCE'] = path\n             run_script_with_cache(args.file, shell.execer, glb=shell.ctx,\n                                   loc=None, mode='exec')\n", "issue": "Invalid sys.argv when running a xonsh script\n``` sh\n$ cat test.py\n#!/usr/bin/env python3\nimport sys\nprint(sys.argv)\n$ ./test.py --hello world\n['./test.py', '--hello', 'world']\n$ python3 test.py --hello world\n['test.py', '--hello', 'world']\n$ sed -i s/python3/xonsh/ test.py\n$ ./test.py --hello world\n['--hello', 'world']\n$ xonsh test.py --hello world\n['--hello', 'world']\n$ execx($(cat test.py))\n['/usr/local/bin/xonsh']\n$\n```\n\nAs you can see, program name is not passed into `argv[0]`. This behaviour differs from _every other_ existing programming language, including Python. Thus, none of the option parsing libraries work with default settings, since they try to use `sys.argv[1:]`.\nHoping this is a bug that's going to be fixed, I'm using the following workaround for now:\n\n``` py\nif semver.match(re.search(r\"([\\w.-]+)\\W*$\", $(xonsh --version)).group(1), \"<=0.4.4\"):\n    args = sys.argv\nelse:\n    args = sys.argv[1:]\n```\n\nBy the way, why does `xonsh --version` print a `repr` of a tuple?\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The main xonsh script.\"\"\"\nimport os\nimport sys\nimport enum\nimport argparse\nimport builtins\nimport contextlib\n\nfrom xonsh import __version__\nfrom xonsh.lazyasd import lazyobject\nfrom xonsh.shell import Shell\nfrom xonsh.pretty import pretty\nfrom xonsh.proc import HiddenCompletedCommand\nfrom xonsh.jobs import ignore_sigtstp\nfrom xonsh.tools import setup_win_unicode_console, print_color\nfrom xonsh.platform import HAS_PYGMENTS, ON_WINDOWS\nfrom xonsh.codecache import run_script_with_cache, run_code_with_cache\nfrom xonsh.xonfig import xonfig_main\nfrom xonsh.lazyimps import pygments, pyghooks\n\n\ndef get_setproctitle():\n    \"\"\"Proxy function for loading process title\"\"\"\n    try:\n        from setproctitle import setproctitle as spt\n    except ImportError:\n        return\n    return spt\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        msg = '{0!r} must be a valid path to a file'.format(s)\n        raise argparse.ArgumentTypeError(msg)\n    return s\n\n\n@lazyobject\ndef parser():\n    p = argparse.ArgumentParser(description='xonsh', add_help=False)\n    p.add_argument('-h', '--help',\n                   dest='help',\n                   action='store_true',\n                   default=False,\n                   help='show help and exit')\n    p.add_argument('-V', '--version',\n                   dest='version',\n                   action='store_true',\n                   default=False,\n                   help='show version information and exit')\n    p.add_argument('-c',\n                   help=\"Run a single command and exit\",\n                   dest='command',\n                   required=False,\n                   default=None)\n    p.add_argument('-i', '--interactive',\n                   help='force running in interactive mode',\n                   dest='force_interactive',\n                   action='store_true',\n                   default=False)\n    p.add_argument('-l', '--login',\n                   help='run as a login shell',\n                   dest='login',\n                   action='store_true',\n                   default=False)\n    p.add_argument('--config-path',\n                   help='specify a custom static configuration file',\n                   dest='config_path',\n                   default=None,\n                   type=path_argument)\n    p.add_argument('--no-rc',\n                   help=\"Do not load the .xonshrc files\",\n                   dest='norc',\n                   action='store_true',\n                   default=False)\n    p.add_argument('--no-script-cache',\n                   help=\"Do not cache scripts as they are run\",\n                   dest='scriptcache',\n                   action='store_false',\n                   default=True)\n    p.add_argument('--cache-everything',\n                   help=\"Use a cache, even for interactive commands\",\n                   dest='cacheall',\n                   action='store_true',\n                   default=False)\n    p.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                   action='append',\n                   default=None)\n    p.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)\n    p.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)\n    p.add_argument('args',\n                   metavar='args',\n                   help='Additional arguments to the script specified '\n                        'by script-file',\n                   nargs=argparse.REMAINDER,\n                   default=[])\n    return p\n\n\ndef _pprint_displayhook(value):\n    if value is None:\n        return\n    builtins._ = None  # Set '_' to None to avoid recursion\n    if isinstance(value, HiddenCompletedCommand):\n        builtins._ = value\n        return\n    env = builtins.__xonsh_env__\n    if env.get('PRETTY_PRINT_RESULTS'):\n        printed_val = pretty(value)\n    else:\n        printed_val = repr(value)\n    if HAS_PYGMENTS and env.get('COLOR_RESULTS'):\n        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))\n        print_color(tokens)\n    else:\n        print(printed_val)  # black & white case\n    builtins._ = value\n\n\nclass XonshMode(enum.Enum):\n    single_command = 0\n    script_from_file = 1\n    script_from_stdin = 2\n    interactive = 3\n\n\ndef premain(argv=None):\n    \"\"\"Setup for main xonsh entry point, returns parsed arguments.\"\"\"\n    if argv is None:\n        argv = sys.argv[1:]\n    setproctitle = get_setproctitle()\n    if setproctitle is not None:\n        setproctitle(' '.join(['xonsh'] + argv))\n    builtins.__xonsh_ctx__ = {}\n    args = parser.parse_args(argv)\n    if args.help:\n        parser.print_help()\n        parser.exit()\n    if args.version:\n        version = '/'.join(('xonsh', __version__)),\n        print(version)\n        parser.exit()\n    shell_kwargs = {'shell_type': args.shell_type,\n                    'completer': False,\n                    'login': False,\n                    'scriptcache': args.scriptcache,\n                    'cacheall': args.cacheall,\n                    'ctx': builtins.__xonsh_ctx__}\n    if args.login:\n        shell_kwargs['login'] = True\n    if args.config_path is not 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    builtins.__xonsh_shell__ = Shell(**shell_kwargs)\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'] = args.force_interactive\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    if argv is None:\n        argv = sys.argv[1:]\n    args = premain(argv)\n    env = builtins.__xonsh_env__\n    shell = builtins.__xonsh_shell__\n    if args.mode == XonshMode.interactive:\n        # enter the shell\n        env['XONSH_INTERACTIVE'] = True\n        ignore_sigtstp()\n        if (env['XONSH_INTERACTIVE'] and\n                not env['LOADED_CONFIG'] and\n                not any(os.path.isfile(i) for i in env['XONSHRC'])):\n            print('Could not find xonsh configuration or run control files.',\n                  file=sys.stderr)\n            xonfig_main(['wizard', '--confirm'])\n        shell.shell.cmdloop()\n    elif args.mode == XonshMode.single_command:\n        # run a single command and exit\n        run_code_with_cache(args.command.lstrip(), shell.execer, mode='single')\n    elif args.mode == XonshMode.script_from_file:\n        # run a script contained in a file\n        path = os.path.abspath(os.path.expanduser(args.file))\n        if os.path.isfile(path):\n            sys.argv = args.args\n            env['ARGS'] = [args.file] + args.args\n            env['XONSH_SOURCE'] = path\n            run_script_with_cache(args.file, shell.execer, glb=shell.ctx,\n                                  loc=None, mode='exec')\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        run_code_with_cache(code, shell.execer, glb=shell.ctx, loc=None,\n                            mode='exec')\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    if hasattr(builtins, '__xonsh_shell__'):\n        del builtins.__xonsh_shell__\n\n\n@contextlib.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", "path": "xonsh/main.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The main xonsh script.\"\"\"\nimport os\nimport sys\nimport enum\nimport argparse\nimport builtins\nimport contextlib\n\nfrom xonsh import __version__\nfrom xonsh.lazyasd import lazyobject\nfrom xonsh.shell import Shell\nfrom xonsh.pretty import pretty\nfrom xonsh.proc import HiddenCompletedCommand\nfrom xonsh.jobs import ignore_sigtstp\nfrom xonsh.tools import setup_win_unicode_console, print_color\nfrom xonsh.platform import HAS_PYGMENTS, ON_WINDOWS\nfrom xonsh.codecache import run_script_with_cache, run_code_with_cache\nfrom xonsh.xonfig import xonfig_main\nfrom xonsh.lazyimps import pygments, pyghooks\n\n\ndef get_setproctitle():\n    \"\"\"Proxy function for loading process title\"\"\"\n    try:\n        from setproctitle import setproctitle as spt\n    except ImportError:\n        return\n    return spt\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        msg = '{0!r} must be a valid path to a file'.format(s)\n        raise argparse.ArgumentTypeError(msg)\n    return s\n\n\n@lazyobject\ndef parser():\n    p = argparse.ArgumentParser(description='xonsh', add_help=False)\n    p.add_argument('-h', '--help',\n                   dest='help',\n                   action='store_true',\n                   default=False,\n                   help='show help and exit')\n    p.add_argument('-V', '--version',\n                   dest='version',\n                   action='store_true',\n                   default=False,\n                   help='show version information and exit')\n    p.add_argument('-c',\n                   help=\"Run a single command and exit\",\n                   dest='command',\n                   required=False,\n                   default=None)\n    p.add_argument('-i', '--interactive',\n                   help='force running in interactive mode',\n                   dest='force_interactive',\n                   action='store_true',\n                   default=False)\n    p.add_argument('-l', '--login',\n                   help='run as a login shell',\n                   dest='login',\n                   action='store_true',\n                   default=False)\n    p.add_argument('--config-path',\n                   help='specify a custom static configuration file',\n                   dest='config_path',\n                   default=None,\n                   type=path_argument)\n    p.add_argument('--no-rc',\n                   help=\"Do not load the .xonshrc files\",\n                   dest='norc',\n                   action='store_true',\n                   default=False)\n    p.add_argument('--no-script-cache',\n                   help=\"Do not cache scripts as they are run\",\n                   dest='scriptcache',\n                   action='store_false',\n                   default=True)\n    p.add_argument('--cache-everything',\n                   help=\"Use a cache, even for interactive commands\",\n                   dest='cacheall',\n                   action='store_true',\n                   default=False)\n    p.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                   action='append',\n                   default=None)\n    p.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)\n    p.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)\n    p.add_argument('args',\n                   metavar='args',\n                   help='Additional arguments to the script specified '\n                        'by script-file',\n                   nargs=argparse.REMAINDER,\n                   default=[])\n    return p\n\n\ndef _pprint_displayhook(value):\n    if value is None:\n        return\n    builtins._ = None  # Set '_' to None to avoid recursion\n    if isinstance(value, HiddenCompletedCommand):\n        builtins._ = value\n        return\n    env = builtins.__xonsh_env__\n    if env.get('PRETTY_PRINT_RESULTS'):\n        printed_val = pretty(value)\n    else:\n        printed_val = repr(value)\n    if HAS_PYGMENTS and env.get('COLOR_RESULTS'):\n        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))\n        print_color(tokens)\n    else:\n        print(printed_val)  # black & white case\n    builtins._ = value\n\n\nclass XonshMode(enum.Enum):\n    single_command = 0\n    script_from_file = 1\n    script_from_stdin = 2\n    interactive = 3\n\n\ndef premain(argv=None):\n    \"\"\"Setup for main xonsh entry point, returns parsed arguments.\"\"\"\n    if argv is None:\n        argv = sys.argv[1:]\n    setproctitle = get_setproctitle()\n    if setproctitle is not None:\n        setproctitle(' '.join(['xonsh'] + argv))\n    builtins.__xonsh_ctx__ = {}\n    args = parser.parse_args(argv)\n    if args.help:\n        parser.print_help()\n        parser.exit()\n    if args.version:\n        version = '/'.join(('xonsh', __version__))\n        print(version)\n        parser.exit()\n    shell_kwargs = {'shell_type': args.shell_type,\n                    'completer': False,\n                    'login': False,\n                    'scriptcache': args.scriptcache,\n                    'cacheall': args.cacheall,\n                    'ctx': builtins.__xonsh_ctx__}\n    if args.login:\n        shell_kwargs['login'] = True\n    if args.config_path is not 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    builtins.__xonsh_shell__ = Shell(**shell_kwargs)\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'] = args.force_interactive\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    if argv is None:\n        argv = sys.argv[1:]\n    args = premain(argv)\n    env = builtins.__xonsh_env__\n    shell = builtins.__xonsh_shell__\n    if args.mode == XonshMode.interactive:\n        # enter the shell\n        env['XONSH_INTERACTIVE'] = True\n        ignore_sigtstp()\n        if (env['XONSH_INTERACTIVE'] and\n                not env['LOADED_CONFIG'] and\n                not any(os.path.isfile(i) for i in env['XONSHRC'])):\n            print('Could not find xonsh configuration or run control files.',\n                  file=sys.stderr)\n            xonfig_main(['wizard', '--confirm'])\n        shell.shell.cmdloop()\n    elif args.mode == XonshMode.single_command:\n        # run a single command and exit\n        run_code_with_cache(args.command.lstrip(), shell.execer, mode='single')\n    elif args.mode == XonshMode.script_from_file:\n        # run a script contained in a file\n        path = os.path.abspath(os.path.expanduser(args.file))\n        if os.path.isfile(path):\n            sys.argv = [args.file] + args.args\n            env['ARGS'] = sys.argv[:]  # $ARGS is not sys.argv\n            env['XONSH_SOURCE'] = path\n            run_script_with_cache(args.file, shell.execer, glb=shell.ctx,\n                                  loc=None, mode='exec')\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        run_code_with_cache(code, shell.execer, glb=shell.ctx, loc=None,\n                            mode='exec')\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    if hasattr(builtins, '__xonsh_shell__'):\n        del builtins.__xonsh_shell__\n\n\n@contextlib.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", "path": "xonsh/main.py"}]}