Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 11개 있습니다.)
개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
; https://www.sysnet.pe.kr/2/0/12752

개발 환경 구성: 595. PyCharm - WSL과 연동해 Django App을 윈도우에서 리눅스 대상으로 개발
; https://www.sysnet.pe.kr/2/0/12773

개발 환경 구성: 597. PyCharm - 윈도우 환경에서 WSL을 이용해 파이썬 앱 개발/디버깅하는 방법
; https://www.sysnet.pe.kr/2/0/12789

개발 환경 구성: 598. PyCharm - 원격 프로세스를 디버그하는 방법
; https://www.sysnet.pe.kr/2/0/12798

개발 환경 구성: 599. PyCharm - (반대로) 원격 프로세스가 PyCharm에 디버그 연결하는 방법
; https://www.sysnet.pe.kr/2/0/12800

개발 환경 구성: 601. PyCharm - 다중 프로세스 디버깅 방법
; https://www.sysnet.pe.kr/2/0/12806

스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
; https://www.sysnet.pe.kr/2/0/12823

개발 환경 구성: 603. GoLand - WSL 환경과 연동
; https://www.sysnet.pe.kr/2/0/12825

개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
; https://www.sysnet.pe.kr/2/0/13318

개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
; https://www.sysnet.pe.kr/2/0/13369

개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
; https://www.sysnet.pe.kr/2/0/13489




PyCharm - (반대로) 원격 프로세스가 PyCharm에 디버그 연결하는 방법

일반적으로 비주얼 스튜디오에 익숙한 사용자라면 원격 디버깅이라고 할 때 이전에 설명했던,

PyCharm - 원격 프로세스를 디버그하는 방법
; https://www.sysnet.pe.kr/2/0/12798

방식의 디버깅만을 연상하게 됩니다. 그런데, 특이하게도 PyCharm의 경우 프로세스 측에서 PyCharm IDE로 디버그 연결을 하는 방법을 함께 제공합니다.

이런 문제는, 아마도 지난 글에 소개한,

파이썬 - WSGI를 만족하는 최소한의 구현 코드 및 PyCharm에서의 디버깅 방법
; https://www.sysnet.pe.kr/2/0/12794

simple_app과 같은 앱을 uwsgi/gunicorn 등에서 호스팅할 때 디버깅을 원한다면 사용할 수 있는 대안으로써 제공되는 듯합니다. 이와 관련된 공식 문서도 있지만,

debugging a uwsgi python application using pycharm
; https://stackoverflow.com/questions/21257568/debugging-a-uwsgi-python-application-using-pycharm

Remote debugging with the Python remote debug server configuration
; https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config

역시 문서보다 ^^ 직접 상황에 따른 예를 드는 것이 더 이해가 빠르겠지요. 이번에도 "PyCharm - 원격 프로세스를 디버그하는 방법"에서처럼 원격 PC가 있어야겠지만 어차피 설정은 모두 동일하므로 WSL 환경에서 테스트를 하겠습니다.

즉, 원격 PC(또는 WSL)에서 실행한 uwsgi/gunicorn 프로세스에서 호스팅되는 Python App을 디버깅하는 것을 가정하고 설명하겠습니다. ^^




우선, PyCharm IDE에서 새로운 "Run/Debug Configuration"을 "Python Debug Server" 유형으로,

passive_remote_debug_1.png

포트와 IDE host name을 입력해 생성합니다. (이 글에서는 WSL 환경이므로 localhost와 임의의 포트를 지정했습니다. 일반적인 상황이라면, "0.0.0.0"으로 AnyIP로 설정하는 것이 속 편합니다.)

그런 다음, 화면에 나오는 텍스트에서 지시하는 것처럼, 원격 PC(또는 WSL) 측에서 "pydevd-pycharm~=212.4746.96" 구성 요소를 설치하고,

$ pip install pydevd-pycharm~=212.4746.96

원격 PC에서 실행할 스크립트에는 적절한 디버그 시점을 선택해 아래의 스크립트를 추가합니다. (즉, 아래의 경우는 시작하자마자 PyCharm IDE의 디버그 서버로 접속을 시도합니다.)

# main.py

import pydevd_pycharm
pydevd_pycharm.settrace('localhost', port=14444, stdoutToServer=True, stderrToServer=True)


HELLO_WORLD = b"Hello world!\n"


def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [HELLO_WORLD]


def get_wsgi_application():
    return simple_app


application = get_wsgi_application()

자, 이걸로 준비 작업은 끝입니다. 이제 PyCharm은 해당 Configuration의 설정으로 디버그를 시작하면 콘솔 화면에 "Waiting for process connection..."이라고 뜨며 연결을 대기합니다.

이후, WSL 측에서 파이썬 스크립트를 실행하면,

$ python main.py
Could not connect to localhost: 14444
Traceback (most recent call last):
  File "/home/testusr/.local/lib/python3.8/site-packages/_pydevd_bundle/pydevd_comm.py", line 507, in start_client
    s.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    pydevd.settrace('localhost', port=14444, stdoutToServer=True, stderrToServer=True)
  File "/home/testusr/.local/lib/python3.8/site-packages/pydevd.py", line 2696, in settrace
    _locked_settrace(
  File "/home/testusr/.local/lib/python3.8/site-packages/pydevd.py", line 2777, in _locked_settrace
    py_db.connect(host, port)  # Note: connect can raise error.
  File "/home/testusr/.local/lib/python3.8/site-packages/pydevd.py", line 1353, in connect
    s = start_client(host, port)
  File "/home/testusr/.local/lib/python3.8/site-packages/_pydevd_bundle/pydevd_comm.py", line 507, in start_client
    s.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused

(원격 호스트라면 오류 없이 잘 실행이 되었겠지만) 아쉽게도 WSL 환경이라 "Could not connect to localhost - ConnectionRefusedError: [Errno 111] Connection refused" 오류가 발생하는군요. ^^




이에 대한 원인은 WSL 2에서의 네트워크의 특징 때문입니다.

WSL 2의 네트워크 통신 방법
; https://www.sysnet.pe.kr/2/0/12347

즉, WSL 인스턴스 측에서 윈도우 호스트 측으로의 "localhost" 접속이 불가능하므로, PyCharm 측의 "IDE host name" 바인딩을 "localhost"가 아닌 "/etc/resolv.conf"에서 보이는 IP로,

$  cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 172.23.208.1

대체해야 합니다. (혹은 그냥 위에서도 언급했지만 "0.0.0.0"으로 설정합니다.) 물론, 스크립트에서도 변경해주고,

pydevd_pycharm.settrace('172.23.208.1', port=14444, stdoutToServer=True, stderrToServer=True)

다시 실행하면 이번에는 정상적으로 디버깅 연결이 됩니다.




그런데, 디버깅 연결까지는 되었지만 아마도 화면에는 여전히 다음과 같은 식의 오류가 발생할 수 있습니다.

/mnt/d/workshop2/python-wsgi-app/main.py can't be found in project. You can continue debugging, but without the source. To fix that you can do one of the following:


소스 코드를 찾을 수 없다는 것인데, 어쩔 수 없습니다. "Run/Debug Configuration"에서 다음과 같이 매핑을 추가해야 합니다.

passive_remote_debug_2.png

이후 다시 디버깅 연결을 하면 콘솔에는 다음의 메시지와 함께,

Starting debug server at port 14,444
Use the following code to connect to the debugger:
import pydevd_pycharm
pydevd_pycharm.settrace('172.23.208.1', port=14444, stdoutToServer=True, stderrToServer=True)
Waiting for process connection…
Connected to pydev debugger (build 212.4746.96)

정상적으로 main.py가 열리고 pydevd.settrace 호출 다음 라인에서 실행이 멈춰 있는 것을 확인할 수 있습니다.

참고로 PyCharm IDE는 디버깅 서버를 한 번 열어 두면 계속 접속을 받아들이도록 동작합니다. 따라서, 클라이언트 측에서 프로세스를 종료해 연결이 끊겨도 PyCharm 측의 디버그 서버를 다시 실행할 필요 없이 그냥 클라이언트 측 프로세스만 다시 시작해 pydevd.settrace 호출을 하면 PyCharm 디버그 서버에 연결이 됩니다.




이로 인해 다음의 소스 코드를,

import pydevd
pydevd.settrace('172.23.208.1', port=14444, stdoutToServer=True, stderrToServer=True)

HELLO_WORLD = b"Hello world!\n"


def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [HELLO_WORLD]


def get_wsgi_application():
    return simple_app


application = get_wsgi_application()

이전에는 gunicorn으로 실행하는 경우,

$ gunicorn -b 0.0.0.0:18090 main

PyCharm에서 (F5 실행) 디버깅을 할 수 없었지만 이제는 pydevd.settrace의 호출로 인해 디버깅이 가능해졌습니다.

(그건 그렇고, 이건 Visual Studio에도 도입을 했으면... 하는 희망이 생기는군요. ^^)




참고로, 아래와 같이 코딩해도 되지만,

import pydevd_pycharm
pydevd_pycharm.settrace('172.23.208.1', port=14444, stdoutToServer=True, stderrToServer=True)

이렇게 해도 정상적으로 동작을 했습니다.

import pydevd
pydevd.settrace('172.23.208.1', port=14444, stdoutToServer=True, stderrToServer=True)

이에 대한 이력은 잘 모르겠지만 pydevd는 예전 모듈인 것 같고, 하위 호한으로 인해 남겨둔 듯합니다. (혹시 이에 대한 차이를 아시는 분은 덧글 부탁드립니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/22/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241641닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241619닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241632닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241617오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241630오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241478닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241644디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241644오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241743닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241746디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242623오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241819닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241619Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241952닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241708VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241735닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241685닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242016닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...