如何覆盖 PySerial 的“__del__” Python 中的方法?
我设置了一个简单的 Python 脚本来将字符发送到 COM3 上的设备。 (这是在Windows XP上运行的) 设备接收字符很好,但是当脚本结束时,或者我调用
ser.close() #ser is an instance of the `serial` method `Serial`
它将串行端口上的 DTR 线设置为高,重置我的设备。
对此感到困惑,我查阅了 PySerial 文档 (http://pyserial.sourceforge.net/) 并发现Module有一个__del__
方法,该方法在删除Serial实例时调用ser.close()
函数。
有没有办法重写这个 __del__ 方法?
(我不想将设备的重置线与 DTR 线断开)
下面是我正在使用的基本代码:
import serial
ser = serial.Serial()
ser.port = 2 #actually COM3
ser.baudrate = 9600
ser.open()
ser.write("Hello")
ser.close()
I have a simple Python script set up to send Characters to a device on COM3.
(This is running on Windows XP)
The device receives the Characters fine, but when the script ends, or I call
ser.close() #ser is an instance of the `serial` method `Serial`
It sets the DTR Line on the serial port High, Resetting my Device.
Perplexed by this, I poked around in the PySerial Documentation (http://pyserial.sourceforge.net/) and found that the Module has a __del__
method, which calls the ser.close()
function when the Serial instance is deleted.
Is there anyway to Override this __del__
method?
(I would prefer to not have to disconnect the Reset Line of my device from the DTR line)
Below is the basic code I am using:
import serial
ser = serial.Serial()
ser.port = 2 #actually COM3
ser.baudrate = 9600
ser.open()
ser.write("Hello")
ser.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,继续并覆盖它。您可以创建
Serial
的子类并指定一个不执行任何操作的__del__()
方法并使用该子类而不是Serial
,或者删除该子类使用del
语句从实际的Serial
类(猴子修补)中获取方法。前一种方法是首选,但如果您无法控制使用串行端口的代码,则可能需要第二种方法。当然,请确保 __del__() 方法在覆盖它之前不会执行任何其他重要操作。子类化:
Monkey-patching:
如果您有此模块的 Python 源代码(即它不是用 C 编写的),第三种方法是创建您自己的副本,然后对其进行编辑而不这样做。 (您也可以对 C 模块执行此操作,但如果您没有 C 专业知识,则运行它会有点困难。)
当然,更改
__del__()
方法以不调用ser.close()
对您给出的代码没有多大帮助,因为您自己调用ser.close()
。 :-)Sure, go ahead and override it. You can either create a subclass of
Serial
and specify a do-nothing__del__()
method and use the subclass instead ofSerial
, or delete that method from the actualSerial
class (monkey-patching) using thedel
statement. The former method is preferred but the second may be necessary if code you don't have any control over is using the serial port. Be sure the__del__()
method doesn't do anything else important before overriding it, of course.Subclassing:
Monkey-patching:
If you have Python source for this module (i.e. it is not written in C), a third approach would be to create your own copy of it and just edit it not to do that. (You can also do this for C modules, but getting it running is a bit more difficult if you don't have C expertise.)
Of course, changing the
__del__()
method to not callser.close()
isn't going to help much in the code you give, since you're callingser.close()
yourself. :-)你尝试过这样的事情吗?
Have you tried something like this?