如何远程调试Python代码

Python017

如何远程调试Python代码,第1张

JetBrains 公司出品的集成开发环境以制作精良风格一致得到广泛好评,PyCharm 作为其中一款针对 Python 语言的 IDE 给了我很多帮助,感觉比较好用的是这个远程调试。

远程调试的代码部署在远端服务器上,通过网络传输使用本机进行单步调试。实用场景为本机为非 GPU 机器,可以在远端 GPU 服务器上运行程序,观察程序运行过程中,各个变量在断点处的当前值。

本机打开程序,新建一个configuration

如上图所示

类型为远程调试

填写 本机 ip和端口,

python2.x拷贝pycharm-debug.egg到远端机器,python3.x拷贝的是pycharm-debug-py3k.egg

程序中加入

sys.path.append('/path/to/your/remote/pycharm-debug.egg')

import pydevd

pydevd.settrace('172.18.76.241', port=8602, stdoutToServer=True, stderrToServer=True)123

本机先debug此configuration,然后远端再运行,默认断点为pydevd.settrace的下一行

socket.timeout: timed out连接超时,需要你先运行服务端的代码:

sr = ThreadedServer(TestRpyc, hostname = "0.0.0.0", port=9999, auto_register=False)  

sr.start()

添加下hostname试一下。

如果解决了您的问题请采纳!

如果未解决请继续追问

你可以使用python的pexcpct包通过ssh调用远程服务器指令:

import pxssh

import getpass

try:

s = pxssh.pxssh()

hostname = raw_input('hostname: ')

username = raw_input('username: ')

password = getpass.getpass('password: ')

s.login (hostname, username, password)

s.sendline ('uptime') # run a command

s.prompt() # match the prompt

print s.before # print everything before the propt.

s.sendline ('ls -l')

s.prompt()

print s.before

s.sendline ('df')

s.prompt()

print s.before

s.logout()

except pxssh.ExceptionPxssh, e:

print "pxssh failed on login."

print str(e)