Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Various debugging scenarios of embedded CPython

lidanger edited this page May 9, 2019 · 2 revisions

下面的 3 个调试场景基于 PTVS 文档中的 2 篇文章:

https://docs.microsoft.com/en-us/visualstudio/python/debugging-mixed-mode https://docs.microsoft.com/en-us/visualstudio/python/debugging-cross-platform-remote

重要的前提条件:

  • 安装带有调试符号和二进制文件的 CPython,如PTVS文档中所述

  • 在 Visual Studio 项目设置中启用本地代码调试

  • Python.NET 2.3.0+ 和 Visual Studio 2017, ptvsd 3.1.0+, Python 3.5+ 分别针对这三个场景进行了测试

  1. 将混合模式跨语言调试器 (Python、托管、本机) 附加到 pythonnet:
  • 切换为 DEBUG=1
  • 手动选择 Managed (4.0+) + Native + Python 调试引擎。

  1. 将 Python 调试器引擎附加到嵌入 pythonnet 的 Python 代码中:
  • 切换为 DEBUG=2
  • 手动选择 Python 调试引擎。

  1. 将 Python 远程调试器 (ptvsd) 附加到嵌入 pythonnet 的 Python 代码中:
  • 切换为 DEBUG=3
  • 在连接类型中选择 Python 远程调试选项 (ptvsd)。
  • 在连接目标中指定传输字符串: tcp://localhost@clr:5678

Program.cs

using System;
using Python.Runtime;
using System.Diagnostics;
using System.Threading;

namespace mixedmode
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic res;
            using (Py.GIL()) {
                Console.WriteLine("embedded Python engine");
                dynamic pymod = Py.Import("mixedmode");
                Console.WriteLine("Imported testing module");
                if ((int)pymod.DEBUG == 1)
                {
                    AttachDebugger(); // 为混合模式调试启用此功能
                }
                res = pymod.pyfunc();
            }
            Console.WriteLine(res);
        }
        static void AttachDebugger()
        {
            Console.WriteLine("waiting for .NET debugger to attach");
            while (!Debugger.IsAttached)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine(".NET debugger is attached");

        }
    }
}

mixedmode.py

DEBUG=2 # 1 - 混合模式跨语言调试器
        # 2 - 附加 Python 调试器
        # 3 - ptvsd 远程调试

import clr

if DEBUG==2:
    import sys
    import time
    while not sys.gettrace():
        time.sleep(0.1)

elif DEBUG==3:
    import ptvsd
    ptvsd.enable_attach('clr')
    ptvsd.wait_for_attach()

def pyfunc(args=None):
    if args:
        return args
    else:
        return "testing"