我正在寻找一种方法将异常的可打印输出更改为愚蠢的消息,以便了解有关 python 内部结构的更多信息(并与朋友搞混;),但到目前为止还没有成功。
考虑以下代码
try:
x # is not defined
except NameError as exc:
print(exc)
Run Code Online (Sandbox Code Playgroud)
代码应输出 name 'x' is not defined
我希望将输出更改为the name 'x' you suggested is not yet defined, my lord. Improve your coding skills.
到目前为止,我明白你不能改变,__builtins__因为它们被“烘焙”为 C 代码,除非:
我已经尝试了两种解决方案,但没有成功:
禁果解决方案:
from forbiddenfruit import curse
curse(BaseException, 'repr', lambda self: print("Test message for repr"))
curse(BaseException, 'str', lambda self: print("Test message for str"))
try:
x
except NameError as exc:
print(exc.str()) # Works, shows test …Run Code Online (Sandbox Code Playgroud) 我想创建一个脚本来检测 USB 驱动器插入计算机后的情况,现在只是在 cmd detector中打印。
注意:我在搜索后使用的是 Windows,我发现我需要使用pyudev 包才能与串行端口通信,并且我需要知道 USB 设备的供应商 ID。
我尝试编写以下代码:
import pyudev
context = pyudev.Context()
monitor = Monitor.from_netlink()
# For USB devices
monitor.filter_by(subsystem='usb')
# OR specifically for most USB serial devices
monitor.filter_by(subsystem='tty')
for action, device in monitor:
vendor_id = device.get('ID_VENDOR_ID')
if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100'] or vendor_id in ['USB\\VID_0930&PID_6544']:
print ('Detected {0} for device with vendor ID {1}'.format(action, vendor_id))
Run Code Online (Sandbox Code Playgroud)
但系统崩溃并显示此错误:
import fcntl ModuleNotFoundError: No module named 'fcntl'
Run Code Online (Sandbox Code Playgroud)
我认为 fcntl 仅适用于 Ubuntu,因为我尝试安装该软件包但它不存在。