首先,我想说如果有人能在这里提供帮助,你真是太棒了。
一般问题
我的Python程序需要与MSMQ交互。基本上,我想查看队列,如果队列中没有任何内容,则指定超时。
但是,尽管我尽了最大努力,当队列中先前没有值时,我仍无法让 Peek() 等待超时间隔。 您能指出这段代码中缺少什么吗?
<小时/>我当前的代码
这是我现在的代码:
from socket import gethostname
import win32com.client
import pythoncom
import clr
clr.AddReference("System")
clr.AddReference("System.Messaging")
from System import TimeSpan
from System.Messaging import MessageQueue
# Source: [1]
# [1] https://learn.microsoft.com/en-us/previous-versions/windows/desktop/msmq/ms707027%28v%3dvs.85%29
MQ_DENY_NONE = 0x0
MQ_PEEK_ACCESS = 0x1
MQ_SEND_ACCESS = 0x2
# Set up queue
pythoncom.CoInitialize()
qinfo = win32com.client.Dispatch("MSMQ.MSMQQueueInfo")
qinfo.FormatName = f"direct=os:{gethostname()}\\PRIVATE$\\MyQueue"
queue = qinfo.Open(MQ_PEEK_ACCESS, MQ_DENY_NONE)
# Receive a value
timeout_sec = 1.0
timespan = TimeSpan.FromSeconds(timeout_sec)
label, body = "", ""
# TODO: timeout value does not appear working. It never waits when
# there's no message
if queue.Peek(pythoncom.Empty, pythoncom.Empty, timespan):
msg = queue.Receive() . # Blocking receive --> remove msg from the queue
if msg is not None:
label = msg.Label
body = msg.Body
我运行:inspect.getfullargspec(queue.Peek)
并获取:
FullArgSpec(args=['self', 'WantDestinationQueue', 'WantBody', 'ReceiveTimeout', 'WantConnectorType'], varargs=None, varkw=None, defaults=(<PyOleMissing object at 0x00000147F5D43BD0>, <PyOleMissing object at 0x00000147F5D43BD0>, <PyOleMissing object at 0x00000147F5D43BD0>, <PyOleMissing object at 0x00000147F5D43BD0>), kwonlyargs=[], kwonlydefaults=None, annotations={})
<小时/>
我尝试过的事情
This question :说 ReceiveTimeout=timespan
似乎并不能解决我的问题。
用 pythoncom.Missing
替换 pythoncom.Empty
似乎不起作用
This unanswered question看起来和我的很相似
最佳答案
在原始问题的评论中,@PeterBrittain 建议尝试仅使用:
an integer (in milliseconds) for their timeout
我抽出时间尝试了一下,实际上,它成功了!我发现 float
值也可以工作。以下是一些示例 Python 代码:
timeout_sec = 1.0
queue.Peek(pythoncom.Empty, pythoncom.Empty, timeout_sec * 1000):
谢谢@PeterBrittain!
关于Python通过win32com运行MessageQueue.Peek,如何获得正确的超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652569/