Giter VIP home page Giter VIP logo

ptvsd's Introduction

🛑 ᴘᴛᴠsᴅ ɪs ᴅᴇᴘʀᴇᴄᴀᴛᴇᴅ 🛑

A replacement implementation of DAP for Python is debugpy, which is based on the development branch (5.x) of ptvsd. All future development is going to be happening in debugpy; there will be no further commits to or releases of ptvsd.

If you're using the Python extension for Visual Studio Code, you should be switched to debugpy automatically, so long as you're using an up-to-date version of the extension. Please file any bug reports directly in the debugpy repository.

If you're using Visual Studio 2019 16.5 or later, you should be switched to debugpy automatically. Visual Studio 2019 16.4 or earlier, including Visual Studio 2017, are not compatible with debugpy. We recommend that you upgrade to the latest version of Visual Studio in order to migrate to debugpy.

If you're using ptvsd directly, consider migrating to debugpy. This is required for continued support from the Python extension, and to receive any bug fixes. Issues with ptvsd that can also be reproduced in debugpy should be filed directly in the debugpy repository. Any issues that are specific to ptvsd, and cannot be reproduced with debugpy, will not be fixed in ptvsd.

Python Tools for Visual Studio debug server

Build Status Build Status Coverage GitHub PyPI PyPI

This debugger is based on the Debug Adapter Protocol for VS Code: debugProtocol.json

ptvsd CLI Usage

Debugging a script file

To run a script file with debugging enabled, but without waiting for the debugger to attach (i.e. code starts executing immediately):

-m ptvsd --host localhost --port 5678 myfile.py

To wait until the debugger attaches before running your code, use the --wait switch.

-m ptvsd --host localhost  --port 5678 --wait myfile.py

The --host option specifies the interface on which the debug server is listening for connections. To be able to attach from another machine, make sure that the server is listening on a public interface - using 0.0.0.0 will make it listen on all available interfaces:

-m ptvsd --host 0.0.0.0 --port 5678 myfile.py

This should only be done on secure networks, since anyone who can connect to the specified port can then execute arbitrary code within the debugged process.

To pass arguments to the script, just specify them after the filename. This works the same as with Python itself - everything up to the filename is processed by ptvsd, but everything after that becomes sys.argv of the running process.

Debugging a module

To run a module, use the -m switch instead of filename:

-m ptvsd --host localhost --port 5678 -m mymodule

Same as with scripts, command line arguments can be passed to the module by specifying them after the module name. All other ptvsd switches work identically in this mode; in particular, --wait can be used to block execution until the debugger attaches.

Attaching to a running process by ID

The following command injects the debugger into a process with a given PID that is running Python code. Once the command returns, a ptvsd server is running within the process, as if that process was launched via -m ptvsd itself.

-m ptvsd --host localhost --port 5678 --pid 12345

ptvsd Import usage

Enabling debugging

At the beginning of your script, import ptvsd, and call ptvsd.enable_attach() to start the debug server. The default hostname is 0.0.0.0, and the default port is 5678; these can be overridden by passing a (host, port) tuple as the first argument of enable_attach().

import ptvsd
ptvsd.enable_attach()
...

Waiting for the debugger to attach

Use the ptvsd.wait_for_attach() function to block program execution until the debugger is attached.

import ptvsd
ptvsd.enable_attach()
ptvsd.wait_for_attach()  # blocks execution until debugger is attached
...

breakpoint() function

In Python 3.7 and above, ptvsd supports the standard breakpoint() function. Use ptvsd.break_into_debugger() function for similar behavior and compatibility with older versions of Python (3.6 and below). If the debugger is attached when either of these functions is invoked, it will pause execution on the calling line, as if it had a breakpoint set. If there's no debugger attached, the functions do nothing, and the code continues to execute normally.

import ptvsd
ptvsd.enable_attach()

while True:
    ...
    breakpoint() # or ptvsd.break_into_debugger() on <3.7
    ...

Custom Protocol arguments

Launch request arguments

{
    "debugOptions":  [
            "RedirectOutput",       // Whether to redirect stdout and stderr (see pydevd_comm.CMD_REDIRECT_OUTPUT)
            "WaitOnNormalExit",     // Wait for user input after user code exits normally
            "WaitOnAbnormalExit",   // Wait for user input after user code exits with error
            "Django",               // Enables Django Template debugging
            "Jinja",                // Enables Jinja (Flask) Template debugging
            "FixFilePathCase",      // See FIX_FILE_PATH_CASE in wrapper.py
            "DebugStdLib",          // Whether to enable debugging of standard library functions
            "StopOnEntry",          // Whether to stop at first line of user code
            "ShowReturnValue",      // Show return values of functions
    ]
}

Attach request arguments

{
    "debugOptions":  [
            "RedirectOutput",       // Whether to redirect stdout and stderr (see pydevd_comm.CMD_REDIRECT_OUTPUT)
            "Django",               // Enables Django Template debugging
            "Jinja",                // Enables Jinja (Flask) Template debugging
            "FixFilePathCase",      // See FIX_FILE_PATH_CASE in wrapper.py
            "DebugStdLib",          // Whether to enable debugging of standard library functions
            "WindowsClient",        // Whether client OS is Windows
            "UnixClient",           // Whether client OS is Unix
            "ShowReturnValue",      // Show return values of functions
    ],
    "pathMappings": [
        {
            "localRoot": "C:\\Project\\src",   // Local root  (where source and debugger running)
            "remoteRoot": "/home/smith/proj"   // Remote root (where remote code is running)
        },
        // Add more path mappings
    ]
}

Debugger logging

To enable debugger internal logging via CLI, the --log-dir switch can be used:

-m ptvsd --log-dir path/to/logs ...

When using enable_attach, the same can be done with log_dir argument:

ptvsd.enable_attach(log_dir='path/to/logs')

In both cases, the environment variable PTVSD_LOG_DIR can also be set to the same effect.

When logging is enabled, ptvsd will create a log file with a name ptvsd-<pid>.log in the specified directory, where <pid> is the ID of the process being debugged. When subprocess debugging is enabled, a separate log is created for every subprocess.

ptvsd's People

Contributors

aggmoulik avatar ahaslam avatar anapo14 avatar ayush--s avatar baek9 avatar d3r3kk avatar dhirschfeld avatar dmytrokyrychuk avatar donjayamanne avatar ericsnowcurrently avatar fabioz avatar gargarchit avatar gramster avatar igornovozhilov avatar int19h avatar jeffrimko avatar karthiknadig avatar martinrenou avatar microsoftopensource avatar msftgits avatar rozuur avatar samb avatar scorphus avatar zooba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ptvsd's Issues

Debugging doesn't work on unix

The wrapper.py is hardcoded for debugging on windows only.

    @async_handler
    def on_initialize(self, request, args):
        # TODO: docstring
        cmd = pydevd_comm.CMD_VERSION
        msg = '1.1\tWINDOWS\tID'

Multiprocess debugging support

pydev is currently started in single process mode. we need to pass --multiprocess flag as a command line arg. That may not be enough, we may need custom protocol messages to tell VS/VSC adapter that another process has started.

Arbitrary expression evaluation

This is required to support the watch window, and also Intermediate window in VS. It will also likely be needed by the new debug REPL implementation in VS.

Need to implement EvaluateRequest in the protocol.

Debugger speedups using cython not found

DebugAdapterProcess: Debug adapter stderr: warning: Debugger speedups using cython not found. Run '"C:\ProgramData\Anaconda3\python.exe" "C:\ProgramData\Anaconda3\lib\site-packages\pydevd-1.1.1-py3.6.egg\setup_cython.py" build_ext --inplace' to build.
DebugAdapterProcess: Debug adapter stderr: PYDEVD_FILTER_LIBRARIES False
DebugAdapterProcess: Debug adapter stderr: 
DebugAdapterProcess: Debug adapter stderr: pydev debugger: starting
DebugAdapterProcess: Debug adapter stderr: 
DebugAdapterProcess: Debug adapter stderr: debugger: received >>501	1000000000	1.1	WINDOWS	ID

Raw value retrieval

This is a VS-specific feature that enables the magnifier icon in Locals, Watch etc for certain variables (normally of string and string-like types).

Need to specify rawString in attributes of the corresponding variables.

Handle ModulesRequest

This request is received by debugger for attach only. Launch depends on module events for tracking modules.

Ability to redirect stdout and stderr (tee program output)

The functionality provided by the RedirectOutput debug option in hew older version of PTVSD doesn't seem to be supported by the PyDev debugger.

From what I can tell this functionality is only available in attach scenarios. I guess this is because the debugger (PyDev) is always launched inside a terminal.

FYI - We're also missing the corresponding protocol implementation in the wrapper. I tried implementing this, however it was a moot point as there's no way to launch a program with redirection enabled as there's no way to do this in PyDev (I could be mistaken).

Conditional breakpoints don't work due to pydevd issue

_pydevd_frame_eval.handle_breakpoint always returns True. For conditional breakpoints to work it should return eval result from _pydevd_bundle.pydevd_frame.handle_breakpoint_condition. The issue repros in LiClipse.

SyntaxError when installing ptvsd

setup.py install output shows following errors:

byte-compiling build\bdist.win-amd64\egg\ptvsd\reraise2.py to reraise2.cpython-36.pyc
  File "build\bdist.win-amd64\egg\ptvsd\reraise2.py", line 10
    raise exc_info[0], exc_info[1], exc_info[2]
                     ^
SyntaxError: invalid syntax

and

Extracting ptvsd-4.0.0a1-py3.6.egg to c:\programdata\anaconda3\lib\site-packages
  File "c:\programdata\anaconda3\lib\site-packages\ptvsd-4.0.0a1-py3.6.egg\ptvsd\reraise2.py", line 10
    raise exc_info[0], exc_info[1], exc_info[2]
                     ^
SyntaxError: invalid syntax

Setting values of arbitrary expressions

This is basically the ability to edit the value of the expression (if it is assignable) in Watch. VSC doesn't support this, so it's a VS-only feature.

Need to implement setExpression request.

Depends on #12

On disconnect the python process does not exit with 0

The program 'python.exe' has exited with code -1 (0xffffffff).

Also, adapter logs show that exited and terminated events were not fired. But disconnect was acknowledged:

 1> [DebugAdapter] --> C (disconnect-11): {"command":"disconnect","arguments":{"terminateDebuggee":true},"seq":11,"type":"request"}
 1> [DebugAdapter] <--   R (disconnect-11): {"type": "response", "seq": 13, "request_seq": 11, "success": true, "command": "disconnect", "message": "", "body": {}}

Ending debug session does not terminate PTVSD process running in a terminal

Currently termination of the PTVSD process is a responsibility of the VS Code debug adapter.
This works in scenarios where we're using the debug console (no-terminals involved).

However when debugging a Python program in an external terminal or the VS Code terminal, then stopping the debugger doesn't kill the PTVSD process. Though the program ends, the PTVSD process is still running, hence the terminal doesn't return to the prompt.

Solutions:

  1. Kill PTVSD using the process id.
    Unfortunately VS Code doesn't return the process id of the process (when we send a request to launch the program in a terminal).
  2. PTVSD could kill itself after it sends the response to the disconnect request.
    This would work well with VS and VS Code.
  3. Implement a new protocol that would send the process id back to VS Code.
    Then VS Code could kill the process using this process id.
    This feels like a hack, when 2 would be better.

Setting variable values

This is about editing variable values in the Locals window and equivalents (but not in Watch; i.e. not arbitrary expressions - that one is #15 ).

Need to implement setVariable request.

Handle exception options

This is a value that is sent by VS based on user selections in the Exception Settings window of VS

Errors when running on 2.7 32-bit


DebugAdapterProcess: Debug adapter stderr: pydev debugger: starting
DebugAdapterProcess: Debug adapter stderr: 
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "_pydevd_bundle\pydevd_cython.pyx", line 1065, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__ (_pydevd_bundle/pydevd_cython.c:20641)
DebugAdapterProcess: Debug adapter stderr:     if py_db.not_in_scope(filename):
Exception thrown: 'System.IO.IOException' in System.dll
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 270, in not_in_scope
DebugAdapterProcess: Debug adapter stderr:     return pydevd_utils.not_in_project_roots(filename)
The thread 0x5938 has exited with code 0 (0x0).
DebugAdapterProcess: Debug adapter stderr: AttributeError: 'NoneType' object has no attribute 'not_in_project_roots'
DebugAdapterProcess: Debug adapter exited with code: -1073741510
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "_pydevd_bundle\pydevd_cython.pyx", line 1065, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__ (_pydevd_bundle/pydevd_cython.c:20641)
DebugAdapterProcess: Debug adapter stderr:     if py_db.not_in_scope(filename):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 270, in not_in_scope
DebugAdapterProcess: Debug adapter stderr:     return pydevd_utils.not_in_project_roots(filename)
DebugAdapterProcess: Debug adapter stderr: AttributeError: 'NoneType' object has no attribute 'not_in_project_roots'
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_comm.py", line 290, in run
DebugAdapterProcess: Debug adapter stderr:     self._on_run()
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 100, in _on_run
DebugAdapterProcess: Debug adapter stderr:     time.sleep(0.5) #this one will only start later on (because otherwise we may not have any non-daemon threads
DebugAdapterProcess: Debug adapter stderr: AttributeError: 'NoneType' object has no attribute 'sleep'
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_process_net_command.py", line 326, in process_net_command
DebugAdapterProcess: Debug adapter stderr:     py_db.consolidate_breakpoints(file, id_to_pybreakpoint, breakpoints)
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 606, in consolidate_breakpoints
DebugAdapterProcess: Debug adapter stderr:     for breakpoint_id, pybreakpoint in dict_iter_items(id_to_breakpoint):
DebugAdapterProcess: Debug adapter stderr: TypeError: 'NoneType' object is not callable
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_process_net_command.py", line 326, in process_net_command
DebugAdapterProcess: Debug adapter stderr:     py_db.consolidate_breakpoints(file, id_to_pybreakpoint, breakpoints)
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 606, in consolidate_breakpoints
DebugAdapterProcess: Debug adapter stderr:     for breakpoint_id, pybreakpoint in dict_iter_items(id_to_breakpoint):
DebugAdapterProcess: Debug adapter stderr: TypeError: 'NoneType' object is not callable
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_process_net_command.py", line 326, in process_net_command
DebugAdapterProcess: Debug adapter stderr:     py_db.consolidate_breakpoints(file, id_to_pybreakpoint, breakpoints)
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 606, in consolidate_breakpoints
DebugAdapterProcess: Debug adapter stderr:     for breakpoint_id, pybreakpoint in dict_iter_items(id_to_breakpoint):
DebugAdapterProcess: Debug adapter stderr: TypeError: 'NoneType' object is not callable
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_process_net_command.py", line 326, in process_net_command
DebugAdapterProcess: Debug adapter stderr:     py_db.consolidate_breakpoints(file, id_to_pybreakpoint, breakpoints)
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 606, in consolidate_breakpoints
DebugAdapterProcess: Debug adapter stderr:     for breakpoint_id, pybreakpoint in dict_iter_items(id_to_breakpoint):
DebugAdapterProcess: Debug adapter stderr: TypeError: 'NoneType' object is not callable
DebugAdapterProcess: Debug adapter stderr: Traceback (most recent call last):
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\_pydevd_bundle\pydevd_process_net_command.py", line 569, in process_net_command
DebugAdapterProcess: Debug adapter stderr:     py_db.disable_tracing_while_running_if_frame_eval()
DebugAdapterProcess: Debug adapter stderr:   File "C:\Python27\lib\site-packages\pydevd.py", line 564, in disable_tracing_while_running_if_frame_eval
DebugAdapterProcess: Debug adapter stderr:     pydevd_tracing.settrace_while_running_if_frame_eval(self, self.dummy_trace_dispatch)
DebugAdapterProcess: Debug adapter stderr: AttributeError: 'NoneType' object has no attribute 'settrace_while_running_if_frame_eval'
DebugAdapterProcess: Debug adapter stderr: ```

Variable value includes type

This is a quirk of pydevd - when reporting the value of the variable, it includes type as part of the value. E.g. given x = 123, the value is reported as int: 123. These are displayed as is in PyDev, but for VSC and especially VS (which has a separate type column), we don't want the type - it's redundant, and gets in the way of editing variable value.

It looks like the format is uniform, so we can just drop the part before the colon.

When launching PTVSD fails, debugging stops silently in VS Code Debugger

  • I'm using the ptvsd_launcher.py to launch the debugger
  • I've created a simple python file with mixed indentation (using spaces and tabs)
  • When launching the debugger, the process falls over simply because the code is buggy.
  • However what's interesting is PTVSD has managed to connect and send and receive protocol messages, unfortunately it doesn't know anything about the errors.

Looking at the code, there doesn't seem to be any exception handling around the launching of a file. I could be mistaken.

I could ready stderr output from the process and display that when the process exits.
Though this isn't a clean approach, it isn't really possible today due to the noise printed out into stdout and stderr by pydevd.

@karthiknadig How does PTVS handle this scenario?

Capture Performance Telemetry

In the recent release of VS Code we introduced some changes to capture some telemetry on the performance of the debugger, specifically:

  • How long it takes to launch the debugger
  • How long it takes for the debugger to break after executing the following commands stepIn, stepOut, continue, next

Now, I don't see any code in PTVSD to capture telemetry. Thats fine.
The problem is we'll need this, without this we cannot measure the performance improvements (and this is a must for the first release).

So the question is:

  • Who'll add this telemetry? PTVSD (debugger) or the adapter (the stuff in the middle) layer?
    If this is something we're going to need for VS as well, then it must be done in PTVS.

Exception seen on exit

Exception in thread ptvsd.Client:
Traceback (most recent call last):
  File "C:\USERS\KANADIG\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\15.0_DCFC3D47EXP\EXTENSIONS\MICROSOFT CORPORATION\PYTHON\3.0\debugger\ptvsd\ipcjson.py", line 280, in process_one_message
    msg = self.__message.pop(0)
IndexError: pop from empty list

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 920, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
  File "C:\USERS\KANADIG\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\15.0_DCFC3D47EXP\EXTENSIONS\MICROSOFT CORPORATION\PYTHON\3.0\debugger\ptvsd\ipcjson.py", line 274, in process_messages
    if self.process_one_message():
  File "C:\USERS\KANADIG\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\15.0_DCFC3D47EXP\EXTENSIONS\MICROSOFT CORPORATION\PYTHON\3.0\debugger\ptvsd\ipcjson.py", line 282, in process_one_message
    self._wait_for_message()
  File "C:\USERS\KANADIG\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\15.0_DCFC3D47EXP\EXTENSIONS\MICROSOFT CORPORATION\PYTHON\3.0\debugger\ptvsd\ipcjson.py", line 149, in _wait_for_message
    line = self._buffered_read_line_as_ascii()
  File "C:\USERS\KANADIG\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\15.0_DCFC3D47EXP\EXTENSIONS\MICROSOFT CORPORATION\PYTHON\3.0\debugger\ptvsd\ipcjson.py", line 108, in _buffered_read_line_as_ascii
    temp = self.__socket.recv(1024)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Debugger exits unexpectedly after continue

1> [DebugAdapter] --> C (continue-10): {"command":"continue","arguments":{"threadId":1},"seq":10,"type":"request"}
1> [DebugAdapter] <--   R (continue-10): {"type": "response", "seq": 14, "request_seq": 10, "success": true, "command": "continue", "message": "", "body": {}}
1> ERROR: The debug adapter exited unexpectedly.

This seems to occur after hitting last breakpoint (continue to end scenario). From the log it appears no exited event is generated.

Running a python 2.7 program to completion ends with an error

When running a python program to completion (without any breakpoints), the program ends with an error output.

  • Python program has a simple print statement print("hello world")
  • Debug the above program without any break points
  • It runs to completion with the following printed in the terminal window:
Traceback (most recent call last):
  File "_pydevd_bundle\pydevd_cython.pyx", line 1065, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__ (_pydevd_bundle/pydevd_cython.c:20641)
  File "/Users/donjayamanne/anaconda3/envs/py27/lib/python2.7/site-packages/pydevd.py", line 270, in not_in_scope
    return pydevd_utils.not_in_project_roots(filename)
AttributeError: 'NoneType' object has no attribute 'not_in_project_roots'
Traceback (most recent call last):
  File "_pydevd_bundle\pydevd_cython.pyx", line 1065, in _pydevd_bundle.pydevd_cython.ThreadTracer.__call__ (_pydevd_bundle/pydevd_cython.c:20641)
  File "/Users/donjayamanne/anaconda3/envs/py27/lib/python2.7/site-packages/pydevd.py", line 270, in not_in_scope
    return pydevd_utils.not_in_project_roots(filename)
AttributeError: 'NoneType' object has no attribute 'not_in_project_roots'

Note: This works perfectly well in Python 3.6

Who should terminate the debugger?

@ericsnowcurrently @int19h @karthiknadig

When terminating the debugger using VS Code, the disconnect request is sent by the client (VS Code).
Currently this request is handled and a response is sent back by PTVSD, but nothing happens.

However VS Code expects two other things to take place:

  • terminated event needs to be sent back (separate issue and PR for this #36)
  • The process should end (if it was launched)

Looking at the existing code, PTVSD doesn't terminate itself.

So the question is who is responsible for terminating the debugger (the PTVSD/debugger process):

  • Should PTVSD terminate its own process when it receives the disconnect request
    I believe this is the right place (as this is where the protcol is handled and responses are sent).
  • Should the VS Code adapter proxy code (the code I'm writing) be responsible for terminating this PTVSD process?

runInterminal response not being handled

microsoft/vscode-python#746

@int19h @ericsnowcurrently

When debugging a Python app using the external terminal or terminal integrated into VS Code, PTVSD does not handle the response sent to it. The response is below.
{"type":"response","seq":3,"command":"runInTerminal","request_seq":2,"success":true}

Note, the request was not sent by PTVSD, it was sent by the typescript code (adapter) to launch the PTVSD (debugger in a terminal). This is a protocol request sent to VS Code.

The chain of events is as follows:

  • VS Code sends initialize request to type script debug adapter

  • We respond with list of capabilities

  • Then, we get the launch request from VS Code, type script debug adapter handles this

  • Type script debug adapter sees that the app needs to be launched in a terminal, hence a runInTerminal request is sent to VS Code

  • VS Code launches the app in the terminal

  • PTVSD starts processing requests, by replying back with the initialized event

  • As soon as this event received from PTVSD, typescript debugger will then take VS Code and connect it directly to PTVSD. (i.e. they communicate with each other, streams are piped and typescript debugger is out of the pic).

  • The problem is VS code , sends a couple of requests and responses to PTVSD

  • VS Code sends the response to runInTerminal and a couple of other requests (these are all sent together)

Type Script debugger could intercept these messages and cut and chop the messages before sending them to PTVSD. However that's quite inefficient (reading the streams, parsing it and splitting, then sending the necessary bit. i.e. we're no longer piping the streams).
Hence this bings in a lot more code that necessary.

So, the easiest and best solution is for PTVSD to handle the runInTerminal response and just ignore it, rather than raising an exception.

incompatible version of pydevd used with ptvsd

I'm trying to hookup vscode with the new debubgger.
This seem to be going well, except until I try to add a breakpoint, thats when things fall over.

I'm getting the following error:

Traceback (most recent call last):
  File "/Users/donjayamanne/anaconda3/envs/py36/lib/python3.6/site-packages/_pydevd_bundle/pydevd_process_net_command.py", line 274, in process_net_command
    breakpoint_id = line = int(line)
ValueError: invalid literal for int() with base 10: '/Users/donjayamanne/Desktop/Development/vscode/ptvsd/main.py'

Looking at our code and PydDevd, we're not building the breakpoints correctly.
or, i'm doing something completely wrong

Here's what I've found:

  • We're building the internal protocol message using the following format:
            msgfmt = '{}\tpython-line\t{}\t{}\tNone\t{}\tNone'
            vsc_bpid = self.bp_map.add(
                    lambda vsc_bpid: (path, vsc_bpid))
            msg = msgfmt.format(vsc_bpid, path, line,
                                src_bp.get('condition', None))

See https://github.com/Microsoft/ptvsd/blob/master/ptvsd/wrapper.py#L556

type, file, line, func_name, suspend_policy, condition, expression = text.split('\t', 6)

I.e. the first item vsc_bpid is no longer necessary.

I managed to get things going by changing the format to msgfmt = 'python-line\t{}\t{}\tNone\tNone\t{}\tNone'.

Obviously this is not correct for two reasons:

  • How is it working for everyone else but me without this change?
    (and this is why I believe I'm doing something wrong).
  • The id mapping is now incorrect (hence removing breakpoints doesn't work)

IndexError inside IPC-JSON code when stopping debugging

Traceback (most recent call last):
  File "C:\git\ptvsd\ptvsd\wrapper.py", line 372, in done
    fut.result()
  File "C:\git\ptvsd\ptvsd\futures.py", line 39, in result
    reraise(self._exc_info)
  File "C:\git\ptvsd\ptvsd\reraise3.py", line 11, in reraise
    raise exc_info[1].with_traceback(exc_info[2])
  File "C:\git\ptvsd\ptvsd\futures.py", line 148, in callback
    x = it.send(fut.result())
  File "C:\git\ptvsd\ptvsd\wrapper.py", line 531, in on_variables
    xml = untangle.parse(resp_args).xml
  File "C:\Python\3.6-32\lib\site-packages\untangle.py", line 182, in parse
    parser.parse(StringIO(filename))
  File "C:\Python\3.6-32\lib\xml\sax\expatreader.py", line 111, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "C:\Python\3.6-32\lib\xml\sax\xmlreader.py", line 125, in parse
    self.feed(buffer)
  File "C:\Python\3.6-32\lib\xml\sax\expatreader.py", line 221, in feed
    self._err_handler.fatalError(exc)
  File "C:\Python\3.6-32\lib\xml\sax\handler.py", line 38, in fatalError
    raise exception
xml.sax._exceptions.SAXParseException: <unknown>:1:0: syntax error
Exception in thread ptvsd.Client:
Traceback (most recent call last):
  File "C:\git\ptvsd\ptvsd\ipcjson.py", line 280, in process_one_message
    msg = self.__message.pop(0)
IndexError: pop from empty list

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python\3.6-32\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Python\3.6-32\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:\git\ptvsd\ptvsd\ipcjson.py", line 274, in process_messages
    if self.process_one_message():
  File "C:\git\ptvsd\ptvsd\ipcjson.py", line 282, in process_one_message
    self._wait_for_message()
  File "C:\git\ptvsd\ptvsd\ipcjson.py", line 149, in _wait_for_message
    line = self._buffered_read_line_as_ascii()
  File "C:\git\ptvsd\ptvsd\ipcjson.py", line 108, in _buffered_read_line_as_ascii
    temp = self.__socket.recv(1024)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

Error on F5 with latest master

---------------------------
Microsoft Visual Studio
---------------------------
Traceback (most recent call last):
  File "G:\pyenv\test1\lib\site-packages\ptvsd\ipcjson.py", line 319, in on_request
    target(request, args)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\wrapper.py", line 288, in f
    fut = m(self, self.loop, *args, **kwargs)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\futures.py", line 133, in g
    it = f(self, *args, **kwargs)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\wrapper.py", line 519, in on_setBreakpoints
    msg = msgfmt.format(vsc_bpid, path. line)
AttributeError: 'str' object has no attribute 'line'
---------------------------
OK   
---------------------------

Launching PTVSD debugger from VS Code

After having a chat with @karthiknadig I learnt that I dont and can't use ptvsd_launcher.py found in PTVS (Visual Studio), instead I can just use the PTVSD module.

This works, and I'm able to get the debugger working in VS Code as follows:
python -m ptvsd --port 8788 --file main.py

However, ptvsd_launcher.py does a lot more than just launching the debugger.

  • It sets the cwd
  • It determines how the code is to be rune (file, module or plain text)
  • It parses the debug options

All of this is done and necessary stuff then passed onto PTVSD (debug function in debugger.py).
With VS Code not utilizing ptvsd_launcher.py, it feels like the responsibility falls on VS Code (our adapter) to to the above.

@ericsnowcurrently @int19h @karthiknadig
Please could someone confirm this.

Unable to update variable in debug console

  • Debug program:
a = 1
b = 2
  • Break on the second line
  • in Debug Console of VS Code enter the following text:
    a = 9
  • You'll now get the following error:
    SyntaxError('invalid syntax', ('<string>', 1, 3, 'x = 123'))

Basically we're unable to update the value of a variable.

Error message shown after python exits

This is the error message I get after the script i a executing is done.

---------------------------
Microsoft Visual Studio
---------------------------
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.



An existing connection was forcibly closed by the remote host
---------------------------
OK   
---------------------------

breakpoint id not found

image

code:


# FB - 201104096
import math


# First Order ODE (y' = f(x, y)) Solver using Euler method
# xa: initial value of independent variable
# xb: final value of independent variable
# ya: initial value of dependent variable
# n : number of steps (higher the better)
# Returns value of y at xb. 
def Euler(f, xa, xb, ya, n):
      h = (xb - xa) / float(n)
      x = xa
      y = ya
      for i in range(n):
          y += h * f(x, y)
          x += h
      return y

# Second Order ODE (y'' = f(x, y, y')) Solver using Euler method
# y1a: initial value of first derivative of dependent variable
def Euler2(f, xa, xb, ya, y1a, n):
      h = (xb - xa) / float(n)
      x = xa
      y = ya
      y1 = y1a
      for i in range(n):
          y1 += h * f(x, y, y1)
          y += h * y1
          x += h
      return y

if __name__ == "__main__":
    print( Euler(lambda x, y: math.cos(x) + math.sin(y), 0, 1, 1, 1000))
    print( Euler2(lambda x, y, y1: math.sin(x * y) - y1, 0, 1, 1, 1, 1000))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.