We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Args passed to user script on 'start without debugging' contains ptvsd args
## Environment data

- PTVSD version: Master
- OS and version: Windows 10
- Python version (& distribution if applicable, e.g. Anaconda): Any
- Using VS Code or Visual Studio: VSC

## Actual behavior

```
['c:\\Users\\kanadig\\.vscode\\extensions\\ms-python.python-2018.6.0\\pythonFiles\\experimental\\ptvsd\\ptvsd\\__main__.py', '--nodebug', '--host', 'localhost', '--port', '51225', 'c:\\scratch\\test.py', '--one', '--two', '--three']
```

## Expected  behavior

```
['c:\\scratch\\test.py', '--one', '--two', '--three']
```

## Steps to reproduce:
1. Create a script file with this content:
```python
import sys
print(sys.argv)
```
2. Add `args` to python experimental launch configuration:
```json
{
    "name": "PyExp: Current File",
    "type": "pythonExperimental",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "args": ["--one", "--two", "--three"]
}
```
2. Run using **F5** and **Ctrl+F5**, the output should be same.



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ptvsd/__main__.py`
Content:
```
1 # Copyright (c) Microsoft Corporation. All rights reserved.
2 # Licensed under the MIT License. See LICENSE in the project root
3 # for license information.
4 
5 import argparse
6 import os.path
7 import sys
8 
9 from ptvsd._local import debug_main, run_main
10 from ptvsd.socket import Address
11 from ptvsd.version import __version__, __author__  # noqa
12 
13 
14 ##################################
15 # the script
16 
17 """
18 For the PyDevd CLI handling see:
19 
20   https://github.com/fabioz/PyDev.Debugger/blob/master/_pydevd_bundle/pydevd_command_line_handling.py
21   https://github.com/fabioz/PyDev.Debugger/blob/master/pydevd.py#L1450  (main func)
22 """  # noqa
23 
24 PYDEVD_OPTS = {
25     '--file',
26     '--client',
27     #'--port',
28     '--vm_type',
29 }
30 
31 PYDEVD_FLAGS = {
32     '--DEBUG',
33     '--DEBUG_RECORD_SOCKET_READS',
34     '--cmd-line',
35     '--module',
36     '--multiproc',
37     '--multiprocess',
38     '--print-in-debugger-startup',
39     '--save-signatures',
40     '--save-threading',
41     '--save-asyncio',
42     '--server',
43     '--qt-support=auto',
44 }
45 
46 USAGE = """
47   {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT -m MODULE [arg ...]
48   {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT FILENAME [arg ...]
49 """  # noqa
50 
51 
52 PYDEVD_DEFAULTS = {
53     '--qt-support=auto',
54 }
55 
56 
57 def _set_pydevd_defaults(pydevd_args):
58     args_to_append = []
59     for arg in PYDEVD_DEFAULTS:
60         if arg not in pydevd_args:
61             args_to_append.append(arg)
62     return pydevd_args + args_to_append
63 
64 
65 def parse_args(argv=None):
66     """Return the parsed args to use in main()."""
67     if argv is None:
68         argv = sys.argv
69         prog = argv[0]
70         if prog == __file__:
71             prog = '{} -m ptvsd'.format(os.path.basename(sys.executable))
72     else:
73         prog = argv[0]
74     argv = argv[1:]
75 
76     supported, pydevd, script = _group_args(argv)
77     args = _parse_args(prog, supported)
78     pydevd = _set_pydevd_defaults(pydevd)
79     extra = pydevd + ['--']
80     if script:
81         extra += script
82     return args, extra
83 
84 
85 def _group_args(argv):
86     supported = []
87     pydevd = []
88     script = []
89 
90     try:
91         pos = argv.index('--')
92     except ValueError:
93         script = []
94     else:
95         script = argv[pos + 1:]
96         argv = argv[:pos]
97 
98     for arg in argv:
99         if arg == '-h' or arg == '--help':
100             return argv, [], script
101 
102     gottarget = False
103     skip = 0
104     for i in range(len(argv)):
105         if skip:
106             skip -= 1
107             continue
108 
109         arg = argv[i]
110         try:
111             nextarg = argv[i + 1]
112         except IndexError:
113             nextarg = None
114 
115         # TODO: Deprecate the PyDevd arg support.
116         # PyDevd support
117         if gottarget:
118             script = argv[i:] + script
119             break
120         if arg == '--client':
121             arg = '--host'
122         elif arg == '--file':
123             if nextarg is None:  # The filename is missing...
124                 pydevd.append(arg)
125                 continue  # This will get handled later.
126             if nextarg.endswith(':') and '--module' in pydevd:
127                 pydevd.remove('--module')
128                 arg = '-m'
129                 argv[i + 1] = nextarg = nextarg[:-1]
130             else:
131                 arg = nextarg
132                 skip += 1
133 
134         if arg in PYDEVD_OPTS:
135             pydevd.append(arg)
136             if nextarg is not None:
137                 pydevd.append(nextarg)
138             skip += 1
139         elif arg in PYDEVD_FLAGS:
140             pydevd.append(arg)
141         elif arg == '--nodebug':
142             supported.append(arg)
143 
144         # ptvsd support
145         elif arg in ('--host', '--server-host', '--port', '-m'):
146             if arg == '-m':
147                 gottarget = True
148             supported.append(arg)
149             if nextarg is not None:
150                 supported.append(nextarg)
151             skip += 1
152         elif arg in ('--single-session',):
153             supported.append(arg)
154         elif not arg.startswith('-'):
155             supported.append(arg)
156             gottarget = True
157 
158         # unsupported arg
159         else:
160             supported.append(arg)
161             break
162 
163     return supported, pydevd, script
164 
165 
166 def _parse_args(prog, argv):
167     parser = argparse.ArgumentParser(
168         prog=prog,
169         usage=USAGE.format(prog),
170     )
171     parser.add_argument('--nodebug', action='store_true')
172     host = parser.add_mutually_exclusive_group()
173     host.add_argument('--host')
174     host.add_argument('--server-host')
175     parser.add_argument('--port', type=int, required=True)
176 
177     target = parser.add_mutually_exclusive_group(required=True)
178     target.add_argument('-m', dest='module')
179     target.add_argument('filename', nargs='?')
180 
181     parser.add_argument('--single-session', action='store_true')
182     parser.add_argument('-V', '--version', action='version')
183     parser.version = __version__
184 
185     args = parser.parse_args(argv)
186     ns = vars(args)
187 
188     serverhost = ns.pop('server_host', None)
189     clienthost = ns.pop('host', None)
190     if serverhost:
191         args.address = Address.as_server(serverhost, ns.pop('port'))
192     elif not clienthost:
193         if args.nodebug:
194             args.address = Address.as_client(clienthost, ns.pop('port'))
195         else:
196             args.address = Address.as_server(clienthost, ns.pop('port'))
197     else:
198         args.address = Address.as_client(clienthost, ns.pop('port'))
199 
200     module = ns.pop('module')
201     filename = ns.pop('filename')
202     if module is None:
203         args.name = filename
204         args.kind = 'script'
205     else:
206         args.name = module
207         args.kind = 'module'
208     #if argv[-1] != args.name or (module and argv[-1] != '-m'):
209     #    parser.error('script/module must be last arg')
210 
211     return args
212 
213 
214 def main(addr, name, kind, extra=(), nodebug=False, **kwargs):
215     if nodebug:
216         run_main(addr, name, kind, *extra, **kwargs)
217     else:
218         debug_main(addr, name, kind, *extra, **kwargs)
219 
220 
221 if __name__ == '__main__':
222     args, extra = parse_args()
223     main(args.address, args.name, args.kind, extra, nodebug=args.nodebug,
224          singlesession=args.single_session)
225
```

Path: `ptvsd/_local.py`
Content:
```
1 import sys
2 
3 import pydevd
4 
5 from ptvsd.pydevd_hooks import install
6 from ptvsd.runner import run as no_debug_runner
7 from ptvsd.socket import Address
8 
9 
10 ########################
11 # high-level functions
12 
13 def debug_main(address, name, kind, *extra, **kwargs):
14     if kind == 'module':
15         run_module(address, name, *extra, **kwargs)
16     else:
17         run_file(address, name, *extra, **kwargs)
18 
19 
20 def run_main(address, name, kind, *extra, **kwargs):
21     no_debug_runner(address, name, kind == 'module', *extra, **kwargs)
22 
23 
24 ########################
25 # low-level functions
26 
27 def run_module(address, modname, *extra, **kwargs):
28     """Run pydevd for the given module."""
29     addr = Address.from_raw(address)
30     if not addr.isserver:
31         kwargs['singlesession'] = True
32     run = kwargs.pop('_run', _run)
33     prog = kwargs.pop('_prog', sys.argv[0])
34     filename = modname + ':'
35     argv = _run_argv(addr, filename, extra, _prog=prog)
36     argv.insert(argv.index('--file'), '--module')
37     run(argv, addr, **kwargs)
38 
39 
40 def run_file(address, filename, *extra, **kwargs):
41     """Run pydevd for the given Python file."""
42     addr = Address.from_raw(address)
43     if not addr.isserver:
44         kwargs['singlesession'] = True
45     run = kwargs.pop('_run', _run)
46     prog = kwargs.pop('_prog', sys.argv[0])
47     argv = _run_argv(addr, filename, extra, _prog=prog)
48     run(argv, addr, **kwargs)
49 
50 
51 def _run_argv(address, filename, extra, _prog=sys.argv[0]):
52     """Convert the given values to an argv that pydevd.main() supports."""
53     if '--' in extra:
54         pydevd = list(extra[:extra.index('--')])
55         extra = list(extra[len(pydevd) + 1:])
56     else:
57         pydevd = []
58         extra = list(extra)
59 
60     host, port = address
61     argv = [
62         _prog,
63         '--port', str(port),
64     ]
65     if not address.isserver:
66         argv.extend([
67             '--client', host or 'localhost',
68         ])
69     return argv + pydevd + [
70         '--file', filename,
71     ] + extra
72 
73 
74 def _run(argv, addr, _pydevd=pydevd, _install=install, **kwargs):
75     """Start pydevd with the given commandline args."""
76     #print(' '.join(argv))
77 
78     # Pydevd assumes that the "__main__" module is the "pydevd" module
79     # and does some tricky stuff under that assumption.  For example,
80     # when the debugger starts up it calls save_main_module()
81     # (in pydevd_bundle/pydevd_utils.py).  That function explicitly sets
82     # sys.modules["pydevd"] to sys.modules["__main__"] and then sets
83     # the __main__ module to a new one.  This makes some sense since
84     # it gives the debugged script a fresh __main__ module.
85     #
86     # This complicates things for us since we are running a different
87     # file (i.e. this one) as the __main__ module.  Consequently,
88     # sys.modules["pydevd"] gets set to ptvsd/__main__.py.  Subsequent
89     # imports of the "pydevd" module then return the wrong module.  We
90     # work around this by avoiding lazy imports of the "pydevd" module.
91     # We also replace the __main__ module with the "pydevd" module here.
92     if sys.modules['__main__'].__file__ != _pydevd.__file__:
93         sys.modules['__main___orig'] = sys.modules['__main__']
94         sys.modules['__main__'] = _pydevd
95 
96     daemon = _install(_pydevd, addr, **kwargs)
97     sys.argv[:] = argv
98     try:
99         _pydevd.main()
100     except SystemExit as ex:
101         daemon.exitcode = int(ex.code)
102         raise
103
```
--- 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/ptvsd/__main__.py b/ptvsd/__main__.py
--- a/ptvsd/__main__.py
+++ b/ptvsd/__main__.py
@@ -49,19 +49,6 @@
 """  # noqa
 
 
-PYDEVD_DEFAULTS = {
-    '--qt-support=auto',
-}
-
-
-def _set_pydevd_defaults(pydevd_args):
-    args_to_append = []
-    for arg in PYDEVD_DEFAULTS:
-        if arg not in pydevd_args:
-            args_to_append.append(arg)
-    return pydevd_args + args_to_append
-
-
 def parse_args(argv=None):
     """Return the parsed args to use in main()."""
     if argv is None:
@@ -75,7 +62,7 @@
 
     supported, pydevd, script = _group_args(argv)
     args = _parse_args(prog, supported)
-    pydevd = _set_pydevd_defaults(pydevd)
+    # '--' is used in _run_args to extract pydevd specific args
     extra = pydevd + ['--']
     if script:
         extra += script
diff --git a/ptvsd/_local.py b/ptvsd/_local.py
--- a/ptvsd/_local.py
+++ b/ptvsd/_local.py
@@ -7,6 +7,19 @@
 from ptvsd.socket import Address
 
 
+PYDEVD_DEFAULTS = {
+    '--qt-support=auto',
+}
+
+
+def _set_pydevd_defaults(pydevd_args):
+    args_to_append = []
+    for arg in PYDEVD_DEFAULTS:
+        if arg not in pydevd_args:
+            args_to_append.append(arg)
+    return pydevd_args + args_to_append
+
+
 ########################
 # high-level functions
 
@@ -18,7 +31,10 @@
 
 
 def run_main(address, name, kind, *extra, **kwargs):
-    no_debug_runner(address, name, kind == 'module', *extra, **kwargs)
+    addr = Address.from_raw(address)
+    sys.argv[:] = _run_main_argv(name, extra)
+    runner = kwargs.pop('_runner', no_debug_runner)
+    runner(addr, name, kind == 'module', *extra, **kwargs)
 
 
 ########################
@@ -57,6 +73,7 @@
         pydevd = []
         extra = list(extra)
 
+    pydevd = _set_pydevd_defaults(pydevd)
     host, port = address
     argv = [
         _prog,
@@ -71,6 +88,15 @@
     ] + extra
 
 
+def _run_main_argv(filename, extra):
+    if '--' in extra:
+        pydevd = list(extra[:extra.index('--')])
+        extra = list(extra[len(pydevd) + 1:])
+    else:
+        extra = list(extra)
+    return [filename] + extra
+
+
 def _run(argv, addr, _pydevd=pydevd, _install=install, **kwargs):
     """Start pydevd with the given commandline args."""
     #print(' '.join(argv))

{"golden_diff": "diff --git a/ptvsd/__main__.py b/ptvsd/__main__.py\n--- a/ptvsd/__main__.py\n+++ b/ptvsd/__main__.py\n@@ -49,19 +49,6 @@\n \"\"\"  # noqa\n \n \n-PYDEVD_DEFAULTS = {\n-    '--qt-support=auto',\n-}\n-\n-\n-def _set_pydevd_defaults(pydevd_args):\n-    args_to_append = []\n-    for arg in PYDEVD_DEFAULTS:\n-        if arg not in pydevd_args:\n-            args_to_append.append(arg)\n-    return pydevd_args + args_to_append\n-\n-\n def parse_args(argv=None):\n     \"\"\"Return the parsed args to use in main().\"\"\"\n     if argv is None:\n@@ -75,7 +62,7 @@\n \n     supported, pydevd, script = _group_args(argv)\n     args = _parse_args(prog, supported)\n-    pydevd = _set_pydevd_defaults(pydevd)\n+    # '--' is used in _run_args to extract pydevd specific args\n     extra = pydevd + ['--']\n     if script:\n         extra += script\ndiff --git a/ptvsd/_local.py b/ptvsd/_local.py\n--- a/ptvsd/_local.py\n+++ b/ptvsd/_local.py\n@@ -7,6 +7,19 @@\n from ptvsd.socket import Address\n \n \n+PYDEVD_DEFAULTS = {\n+    '--qt-support=auto',\n+}\n+\n+\n+def _set_pydevd_defaults(pydevd_args):\n+    args_to_append = []\n+    for arg in PYDEVD_DEFAULTS:\n+        if arg not in pydevd_args:\n+            args_to_append.append(arg)\n+    return pydevd_args + args_to_append\n+\n+\n ########################\n # high-level functions\n \n@@ -18,7 +31,10 @@\n \n \n def run_main(address, name, kind, *extra, **kwargs):\n-    no_debug_runner(address, name, kind == 'module', *extra, **kwargs)\n+    addr = Address.from_raw(address)\n+    sys.argv[:] = _run_main_argv(name, extra)\n+    runner = kwargs.pop('_runner', no_debug_runner)\n+    runner(addr, name, kind == 'module', *extra, **kwargs)\n \n \n ########################\n@@ -57,6 +73,7 @@\n         pydevd = []\n         extra = list(extra)\n \n+    pydevd = _set_pydevd_defaults(pydevd)\n     host, port = address\n     argv = [\n         _prog,\n@@ -71,6 +88,15 @@\n     ] + extra\n \n \n+def _run_main_argv(filename, extra):\n+    if '--' in extra:\n+        pydevd = list(extra[:extra.index('--')])\n+        extra = list(extra[len(pydevd) + 1:])\n+    else:\n+        extra = list(extra)\n+    return [filename] + extra\n+\n+\n def _run(argv, addr, _pydevd=pydevd, _install=install, **kwargs):\n     \"\"\"Start pydevd with the given commandline args.\"\"\"\n     #print(' '.join(argv))\n", "issue": "Args passed to user script on 'start without debugging' contains ptvsd args\n## Environment data\r\n\r\n- PTVSD version: Master\r\n- OS and version: Windows 10\r\n- Python version (& distribution if applicable, e.g. Anaconda): Any\r\n- Using VS Code or Visual Studio: VSC\r\n\r\n## Actual behavior\r\n\r\n```\r\n['c:\\\\Users\\\\kanadig\\\\.vscode\\\\extensions\\\\ms-python.python-2018.6.0\\\\pythonFiles\\\\experimental\\\\ptvsd\\\\ptvsd\\\\__main__.py', '--nodebug', '--host', 'localhost', '--port', '51225', 'c:\\\\scratch\\\\test.py', '--one', '--two', '--three']\r\n```\r\n\r\n## Expected  behavior\r\n\r\n```\r\n['c:\\\\scratch\\\\test.py', '--one', '--two', '--three']\r\n```\r\n\r\n## Steps to reproduce:\r\n1. Create a script file with this content:\r\n```python\r\nimport sys\r\nprint(sys.argv)\r\n```\r\n2. Add `args` to python experimental launch configuration:\r\n```json\r\n{\r\n    \"name\": \"PyExp: Current File\",\r\n    \"type\": \"pythonExperimental\",\r\n    \"request\": \"launch\",\r\n    \"program\": \"${file}\",\r\n    \"console\": \"integratedTerminal\",\r\n    \"args\": [\"--one\", \"--two\", \"--three\"]\r\n}\r\n```\r\n2. Run using **F5** and **Ctrl+F5**, the output should be same.\r\n\r\n\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport argparse\nimport os.path\nimport sys\n\nfrom ptvsd._local import debug_main, run_main\nfrom ptvsd.socket import Address\nfrom ptvsd.version import __version__, __author__  # noqa\n\n\n##################################\n# the script\n\n\"\"\"\nFor the PyDevd CLI handling see:\n\n  https://github.com/fabioz/PyDev.Debugger/blob/master/_pydevd_bundle/pydevd_command_line_handling.py\n  https://github.com/fabioz/PyDev.Debugger/blob/master/pydevd.py#L1450  (main func)\n\"\"\"  # noqa\n\nPYDEVD_OPTS = {\n    '--file',\n    '--client',\n    #'--port',\n    '--vm_type',\n}\n\nPYDEVD_FLAGS = {\n    '--DEBUG',\n    '--DEBUG_RECORD_SOCKET_READS',\n    '--cmd-line',\n    '--module',\n    '--multiproc',\n    '--multiprocess',\n    '--print-in-debugger-startup',\n    '--save-signatures',\n    '--save-threading',\n    '--save-asyncio',\n    '--server',\n    '--qt-support=auto',\n}\n\nUSAGE = \"\"\"\n  {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT -m MODULE [arg ...]\n  {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT FILENAME [arg ...]\n\"\"\"  # noqa\n\n\nPYDEVD_DEFAULTS = {\n    '--qt-support=auto',\n}\n\n\ndef _set_pydevd_defaults(pydevd_args):\n    args_to_append = []\n    for arg in PYDEVD_DEFAULTS:\n        if arg not in pydevd_args:\n            args_to_append.append(arg)\n    return pydevd_args + args_to_append\n\n\ndef parse_args(argv=None):\n    \"\"\"Return the parsed args to use in main().\"\"\"\n    if argv is None:\n        argv = sys.argv\n        prog = argv[0]\n        if prog == __file__:\n            prog = '{} -m ptvsd'.format(os.path.basename(sys.executable))\n    else:\n        prog = argv[0]\n    argv = argv[1:]\n\n    supported, pydevd, script = _group_args(argv)\n    args = _parse_args(prog, supported)\n    pydevd = _set_pydevd_defaults(pydevd)\n    extra = pydevd + ['--']\n    if script:\n        extra += script\n    return args, extra\n\n\ndef _group_args(argv):\n    supported = []\n    pydevd = []\n    script = []\n\n    try:\n        pos = argv.index('--')\n    except ValueError:\n        script = []\n    else:\n        script = argv[pos + 1:]\n        argv = argv[:pos]\n\n    for arg in argv:\n        if arg == '-h' or arg == '--help':\n            return argv, [], script\n\n    gottarget = False\n    skip = 0\n    for i in range(len(argv)):\n        if skip:\n            skip -= 1\n            continue\n\n        arg = argv[i]\n        try:\n            nextarg = argv[i + 1]\n        except IndexError:\n            nextarg = None\n\n        # TODO: Deprecate the PyDevd arg support.\n        # PyDevd support\n        if gottarget:\n            script = argv[i:] + script\n            break\n        if arg == '--client':\n            arg = '--host'\n        elif arg == '--file':\n            if nextarg is None:  # The filename is missing...\n                pydevd.append(arg)\n                continue  # This will get handled later.\n            if nextarg.endswith(':') and '--module' in pydevd:\n                pydevd.remove('--module')\n                arg = '-m'\n                argv[i + 1] = nextarg = nextarg[:-1]\n            else:\n                arg = nextarg\n                skip += 1\n\n        if arg in PYDEVD_OPTS:\n            pydevd.append(arg)\n            if nextarg is not None:\n                pydevd.append(nextarg)\n            skip += 1\n        elif arg in PYDEVD_FLAGS:\n            pydevd.append(arg)\n        elif arg == '--nodebug':\n            supported.append(arg)\n\n        # ptvsd support\n        elif arg in ('--host', '--server-host', '--port', '-m'):\n            if arg == '-m':\n                gottarget = True\n            supported.append(arg)\n            if nextarg is not None:\n                supported.append(nextarg)\n            skip += 1\n        elif arg in ('--single-session',):\n            supported.append(arg)\n        elif not arg.startswith('-'):\n            supported.append(arg)\n            gottarget = True\n\n        # unsupported arg\n        else:\n            supported.append(arg)\n            break\n\n    return supported, pydevd, script\n\n\ndef _parse_args(prog, argv):\n    parser = argparse.ArgumentParser(\n        prog=prog,\n        usage=USAGE.format(prog),\n    )\n    parser.add_argument('--nodebug', action='store_true')\n    host = parser.add_mutually_exclusive_group()\n    host.add_argument('--host')\n    host.add_argument('--server-host')\n    parser.add_argument('--port', type=int, required=True)\n\n    target = parser.add_mutually_exclusive_group(required=True)\n    target.add_argument('-m', dest='module')\n    target.add_argument('filename', nargs='?')\n\n    parser.add_argument('--single-session', action='store_true')\n    parser.add_argument('-V', '--version', action='version')\n    parser.version = __version__\n\n    args = parser.parse_args(argv)\n    ns = vars(args)\n\n    serverhost = ns.pop('server_host', None)\n    clienthost = ns.pop('host', None)\n    if serverhost:\n        args.address = Address.as_server(serverhost, ns.pop('port'))\n    elif not clienthost:\n        if args.nodebug:\n            args.address = Address.as_client(clienthost, ns.pop('port'))\n        else:\n            args.address = Address.as_server(clienthost, ns.pop('port'))\n    else:\n        args.address = Address.as_client(clienthost, ns.pop('port'))\n\n    module = ns.pop('module')\n    filename = ns.pop('filename')\n    if module is None:\n        args.name = filename\n        args.kind = 'script'\n    else:\n        args.name = module\n        args.kind = 'module'\n    #if argv[-1] != args.name or (module and argv[-1] != '-m'):\n    #    parser.error('script/module must be last arg')\n\n    return args\n\n\ndef main(addr, name, kind, extra=(), nodebug=False, **kwargs):\n    if nodebug:\n        run_main(addr, name, kind, *extra, **kwargs)\n    else:\n        debug_main(addr, name, kind, *extra, **kwargs)\n\n\nif __name__ == '__main__':\n    args, extra = parse_args()\n    main(args.address, args.name, args.kind, extra, nodebug=args.nodebug,\n         singlesession=args.single_session)\n", "path": "ptvsd/__main__.py"}, {"content": "import sys\n\nimport pydevd\n\nfrom ptvsd.pydevd_hooks import install\nfrom ptvsd.runner import run as no_debug_runner\nfrom ptvsd.socket import Address\n\n\n########################\n# high-level functions\n\ndef debug_main(address, name, kind, *extra, **kwargs):\n    if kind == 'module':\n        run_module(address, name, *extra, **kwargs)\n    else:\n        run_file(address, name, *extra, **kwargs)\n\n\ndef run_main(address, name, kind, *extra, **kwargs):\n    no_debug_runner(address, name, kind == 'module', *extra, **kwargs)\n\n\n########################\n# low-level functions\n\ndef run_module(address, modname, *extra, **kwargs):\n    \"\"\"Run pydevd for the given module.\"\"\"\n    addr = Address.from_raw(address)\n    if not addr.isserver:\n        kwargs['singlesession'] = True\n    run = kwargs.pop('_run', _run)\n    prog = kwargs.pop('_prog', sys.argv[0])\n    filename = modname + ':'\n    argv = _run_argv(addr, filename, extra, _prog=prog)\n    argv.insert(argv.index('--file'), '--module')\n    run(argv, addr, **kwargs)\n\n\ndef run_file(address, filename, *extra, **kwargs):\n    \"\"\"Run pydevd for the given Python file.\"\"\"\n    addr = Address.from_raw(address)\n    if not addr.isserver:\n        kwargs['singlesession'] = True\n    run = kwargs.pop('_run', _run)\n    prog = kwargs.pop('_prog', sys.argv[0])\n    argv = _run_argv(addr, filename, extra, _prog=prog)\n    run(argv, addr, **kwargs)\n\n\ndef _run_argv(address, filename, extra, _prog=sys.argv[0]):\n    \"\"\"Convert the given values to an argv that pydevd.main() supports.\"\"\"\n    if '--' in extra:\n        pydevd = list(extra[:extra.index('--')])\n        extra = list(extra[len(pydevd) + 1:])\n    else:\n        pydevd = []\n        extra = list(extra)\n\n    host, port = address\n    argv = [\n        _prog,\n        '--port', str(port),\n    ]\n    if not address.isserver:\n        argv.extend([\n            '--client', host or 'localhost',\n        ])\n    return argv + pydevd + [\n        '--file', filename,\n    ] + extra\n\n\ndef _run(argv, addr, _pydevd=pydevd, _install=install, **kwargs):\n    \"\"\"Start pydevd with the given commandline args.\"\"\"\n    #print(' '.join(argv))\n\n    # Pydevd assumes that the \"__main__\" module is the \"pydevd\" module\n    # and does some tricky stuff under that assumption.  For example,\n    # when the debugger starts up it calls save_main_module()\n    # (in pydevd_bundle/pydevd_utils.py).  That function explicitly sets\n    # sys.modules[\"pydevd\"] to sys.modules[\"__main__\"] and then sets\n    # the __main__ module to a new one.  This makes some sense since\n    # it gives the debugged script a fresh __main__ module.\n    #\n    # This complicates things for us since we are running a different\n    # file (i.e. this one) as the __main__ module.  Consequently,\n    # sys.modules[\"pydevd\"] gets set to ptvsd/__main__.py.  Subsequent\n    # imports of the \"pydevd\" module then return the wrong module.  We\n    # work around this by avoiding lazy imports of the \"pydevd\" module.\n    # We also replace the __main__ module with the \"pydevd\" module here.\n    if sys.modules['__main__'].__file__ != _pydevd.__file__:\n        sys.modules['__main___orig'] = sys.modules['__main__']\n        sys.modules['__main__'] = _pydevd\n\n    daemon = _install(_pydevd, addr, **kwargs)\n    sys.argv[:] = argv\n    try:\n        _pydevd.main()\n    except SystemExit as ex:\n        daemon.exitcode = int(ex.code)\n        raise\n", "path": "ptvsd/_local.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport argparse\nimport os.path\nimport sys\n\nfrom ptvsd._local import debug_main, run_main\nfrom ptvsd.socket import Address\nfrom ptvsd.version import __version__, __author__  # noqa\n\n\n##################################\n# the script\n\n\"\"\"\nFor the PyDevd CLI handling see:\n\n  https://github.com/fabioz/PyDev.Debugger/blob/master/_pydevd_bundle/pydevd_command_line_handling.py\n  https://github.com/fabioz/PyDev.Debugger/blob/master/pydevd.py#L1450  (main func)\n\"\"\"  # noqa\n\nPYDEVD_OPTS = {\n    '--file',\n    '--client',\n    #'--port',\n    '--vm_type',\n}\n\nPYDEVD_FLAGS = {\n    '--DEBUG',\n    '--DEBUG_RECORD_SOCKET_READS',\n    '--cmd-line',\n    '--module',\n    '--multiproc',\n    '--multiprocess',\n    '--print-in-debugger-startup',\n    '--save-signatures',\n    '--save-threading',\n    '--save-asyncio',\n    '--server',\n    '--qt-support=auto',\n}\n\nUSAGE = \"\"\"\n  {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT -m MODULE [arg ...]\n  {0} [-h] [-V] [--nodebug] [--host HOST | --server-host HOST] --port PORT FILENAME [arg ...]\n\"\"\"  # noqa\n\n\ndef parse_args(argv=None):\n    \"\"\"Return the parsed args to use in main().\"\"\"\n    if argv is None:\n        argv = sys.argv\n        prog = argv[0]\n        if prog == __file__:\n            prog = '{} -m ptvsd'.format(os.path.basename(sys.executable))\n    else:\n        prog = argv[0]\n    argv = argv[1:]\n\n    supported, pydevd, script = _group_args(argv)\n    args = _parse_args(prog, supported)\n    # '--' is used in _run_args to extract pydevd specific args\n    extra = pydevd + ['--']\n    if script:\n        extra += script\n    return args, extra\n\n\ndef _group_args(argv):\n    supported = []\n    pydevd = []\n    script = []\n\n    try:\n        pos = argv.index('--')\n    except ValueError:\n        script = []\n    else:\n        script = argv[pos + 1:]\n        argv = argv[:pos]\n\n    for arg in argv:\n        if arg == '-h' or arg == '--help':\n            return argv, [], script\n\n    gottarget = False\n    skip = 0\n    for i in range(len(argv)):\n        if skip:\n            skip -= 1\n            continue\n\n        arg = argv[i]\n        try:\n            nextarg = argv[i + 1]\n        except IndexError:\n            nextarg = None\n\n        # TODO: Deprecate the PyDevd arg support.\n        # PyDevd support\n        if gottarget:\n            script = argv[i:] + script\n            break\n        if arg == '--client':\n            arg = '--host'\n        elif arg == '--file':\n            if nextarg is None:  # The filename is missing...\n                pydevd.append(arg)\n                continue  # This will get handled later.\n            if nextarg.endswith(':') and '--module' in pydevd:\n                pydevd.remove('--module')\n                arg = '-m'\n                argv[i + 1] = nextarg = nextarg[:-1]\n            else:\n                arg = nextarg\n                skip += 1\n\n        if arg in PYDEVD_OPTS:\n            pydevd.append(arg)\n            if nextarg is not None:\n                pydevd.append(nextarg)\n            skip += 1\n        elif arg in PYDEVD_FLAGS:\n            pydevd.append(arg)\n        elif arg == '--nodebug':\n            supported.append(arg)\n\n        # ptvsd support\n        elif arg in ('--host', '--server-host', '--port', '-m'):\n            if arg == '-m':\n                gottarget = True\n            supported.append(arg)\n            if nextarg is not None:\n                supported.append(nextarg)\n            skip += 1\n        elif arg in ('--single-session',):\n            supported.append(arg)\n        elif not arg.startswith('-'):\n            supported.append(arg)\n            gottarget = True\n\n        # unsupported arg\n        else:\n            supported.append(arg)\n            break\n\n    return supported, pydevd, script\n\n\ndef _parse_args(prog, argv):\n    parser = argparse.ArgumentParser(\n        prog=prog,\n        usage=USAGE.format(prog),\n    )\n    parser.add_argument('--nodebug', action='store_true')\n    host = parser.add_mutually_exclusive_group()\n    host.add_argument('--host')\n    host.add_argument('--server-host')\n    parser.add_argument('--port', type=int, required=True)\n\n    target = parser.add_mutually_exclusive_group(required=True)\n    target.add_argument('-m', dest='module')\n    target.add_argument('filename', nargs='?')\n\n    parser.add_argument('--single-session', action='store_true')\n    parser.add_argument('-V', '--version', action='version')\n    parser.version = __version__\n\n    args = parser.parse_args(argv)\n    ns = vars(args)\n\n    serverhost = ns.pop('server_host', None)\n    clienthost = ns.pop('host', None)\n    if serverhost:\n        args.address = Address.as_server(serverhost, ns.pop('port'))\n    elif not clienthost:\n        if args.nodebug:\n            args.address = Address.as_client(clienthost, ns.pop('port'))\n        else:\n            args.address = Address.as_server(clienthost, ns.pop('port'))\n    else:\n        args.address = Address.as_client(clienthost, ns.pop('port'))\n\n    module = ns.pop('module')\n    filename = ns.pop('filename')\n    if module is None:\n        args.name = filename\n        args.kind = 'script'\n    else:\n        args.name = module\n        args.kind = 'module'\n    #if argv[-1] != args.name or (module and argv[-1] != '-m'):\n    #    parser.error('script/module must be last arg')\n\n    return args\n\n\ndef main(addr, name, kind, extra=(), nodebug=False, **kwargs):\n    if nodebug:\n        run_main(addr, name, kind, *extra, **kwargs)\n    else:\n        debug_main(addr, name, kind, *extra, **kwargs)\n\n\nif __name__ == '__main__':\n    args, extra = parse_args()\n    main(args.address, args.name, args.kind, extra, nodebug=args.nodebug,\n         singlesession=args.single_session)\n", "path": "ptvsd/__main__.py"}, {"content": "import sys\n\nimport pydevd\n\nfrom ptvsd.pydevd_hooks import install\nfrom ptvsd.runner import run as no_debug_runner\nfrom ptvsd.socket import Address\n\n\nPYDEVD_DEFAULTS = {\n    '--qt-support=auto',\n}\n\n\ndef _set_pydevd_defaults(pydevd_args):\n    args_to_append = []\n    for arg in PYDEVD_DEFAULTS:\n        if arg not in pydevd_args:\n            args_to_append.append(arg)\n    return pydevd_args + args_to_append\n\n\n########################\n# high-level functions\n\ndef debug_main(address, name, kind, *extra, **kwargs):\n    if kind == 'module':\n        run_module(address, name, *extra, **kwargs)\n    else:\n        run_file(address, name, *extra, **kwargs)\n\n\ndef run_main(address, name, kind, *extra, **kwargs):\n    addr = Address.from_raw(address)\n    sys.argv[:] = _run_main_argv(name, extra)\n    runner = kwargs.pop('_runner', no_debug_runner)\n    runner(addr, name, kind == 'module', *extra, **kwargs)\n\n\n########################\n# low-level functions\n\ndef run_module(address, modname, *extra, **kwargs):\n    \"\"\"Run pydevd for the given module.\"\"\"\n    addr = Address.from_raw(address)\n    if not addr.isserver:\n        kwargs['singlesession'] = True\n    run = kwargs.pop('_run', _run)\n    prog = kwargs.pop('_prog', sys.argv[0])\n    filename = modname + ':'\n    argv = _run_argv(addr, filename, extra, _prog=prog)\n    argv.insert(argv.index('--file'), '--module')\n    run(argv, addr, **kwargs)\n\n\ndef run_file(address, filename, *extra, **kwargs):\n    \"\"\"Run pydevd for the given Python file.\"\"\"\n    addr = Address.from_raw(address)\n    if not addr.isserver:\n        kwargs['singlesession'] = True\n    run = kwargs.pop('_run', _run)\n    prog = kwargs.pop('_prog', sys.argv[0])\n    argv = _run_argv(addr, filename, extra, _prog=prog)\n    run(argv, addr, **kwargs)\n\n\ndef _run_argv(address, filename, extra, _prog=sys.argv[0]):\n    \"\"\"Convert the given values to an argv that pydevd.main() supports.\"\"\"\n    if '--' in extra:\n        pydevd = list(extra[:extra.index('--')])\n        extra = list(extra[len(pydevd) + 1:])\n    else:\n        pydevd = []\n        extra = list(extra)\n\n    pydevd = _set_pydevd_defaults(pydevd)\n    host, port = address\n    argv = [\n        _prog,\n        '--port', str(port),\n    ]\n    if not address.isserver:\n        argv.extend([\n            '--client', host or 'localhost',\n        ])\n    return argv + pydevd + [\n        '--file', filename,\n    ] + extra\n\n\ndef _run_main_argv(filename, extra):\n    if '--' in extra:\n        pydevd = list(extra[:extra.index('--')])\n        extra = list(extra[len(pydevd) + 1:])\n    else:\n        extra = list(extra)\n    return [filename] + extra\n\n\ndef _run(argv, addr, _pydevd=pydevd, _install=install, **kwargs):\n    \"\"\"Start pydevd with the given commandline args.\"\"\"\n    #print(' '.join(argv))\n\n    # Pydevd assumes that the \"__main__\" module is the \"pydevd\" module\n    # and does some tricky stuff under that assumption.  For example,\n    # when the debugger starts up it calls save_main_module()\n    # (in pydevd_bundle/pydevd_utils.py).  That function explicitly sets\n    # sys.modules[\"pydevd\"] to sys.modules[\"__main__\"] and then sets\n    # the __main__ module to a new one.  This makes some sense since\n    # it gives the debugged script a fresh __main__ module.\n    #\n    # This complicates things for us since we are running a different\n    # file (i.e. this one) as the __main__ module.  Consequently,\n    # sys.modules[\"pydevd\"] gets set to ptvsd/__main__.py.  Subsequent\n    # imports of the \"pydevd\" module then return the wrong module.  We\n    # work around this by avoiding lazy imports of the \"pydevd\" module.\n    # We also replace the __main__ module with the \"pydevd\" module here.\n    if sys.modules['__main__'].__file__ != _pydevd.__file__:\n        sys.modules['__main___orig'] = sys.modules['__main__']\n        sys.modules['__main__'] = _pydevd\n\n    daemon = _install(_pydevd, addr, **kwargs)\n    sys.argv[:] = argv\n    try:\n        _pydevd.main()\n    except SystemExit as ex:\n        daemon.exitcode = int(ex.code)\n        raise\n", "path": "ptvsd/_local.py"}]}