我正在尝试在Python的新线程中从dll创建一个COM对象 - 所以我可以在该线程中运行消息泵:
from comtypes.client import CreateObject
import threading
class MessageThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True
def run(self):
print "Thread starting"
connection = CreateObject("IDMessaging.IDMMFileConnection")
print "connection created"
a = CreateObject("IDMessaging.IDMMFileConnection")
print "aConnection created"
t = MessageThread()
t.start()
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误跟踪:
aConnection created
Thread starting
>>> Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\python26\lib\threading.py", line 532, in __bootstrap_inner
self.run()
File "fred.py", line 99, in run
self.connection = CreateObject("IDMessaging.IDMMFileConnection")
File "c:\python26\lib\site-packages\comtypes\client\__init__.py", line 235, in CreateObject
obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface) …Run Code Online (Sandbox Code Playgroud) 我正在包装一个执行阻塞操作(选择)的C函数,然后处理传入的消息.我的理解是,当一个C函数要阻塞时,在允许其他线程运行的同时调用它的正确方法是:
Py_BEGIN_ALLOW_THREADS
blocking_function();
Py_END_ALLOW_THREADS
Run Code Online (Sandbox Code Playgroud)
但是,它发生此函数将回调指针作为参数.在处理由C函数预处理的传入消息时调用此回调.我已经成功地将这个回调包装在一个调用的函数中PyEval_CallObject(),允许我传递一个Python回调.
现在我正在添加线程支持,我想知道是否可以同时:
这会导致问题吗?如果是这样,有办法吗?
谢谢.
我一直在尝试编写一个简单的python应用程序来实现一个工作队列,我发现每个网页都有一些随机的人对它进行评论,你不应该使用python线程因为这个或那个,有人可以帮助我吗?什么是Python线程,我可以使用它吗?如果是哪个lib?标准的还不错吗?
我正在运行一个脚本,它从debian包中提取信息并将其保存在数据库中.
从大约100个包中提取信息后发生错误.错误是"无法启动新线程"为什么我会遇到此错误?可能的解决办法是什么?
这是用于保存数据的代码:
for i in list_pack:
if not i in oblist:
#Creating Packages
slu=slugify(i)
ob=Gbobject()
ob.title=i
ob.slug=slu
ob.content=''
ob.tags=tagname
#with reversion.create_revision():
ob.save()
gb=Gbobject.objects.get(title=i)
gb.objecttypes.add(Objecttype.objects.get(title='Packages'))
gb.sites.add(Site.objects.get_current())
#with reversion.create_revision():
gb.save()
gd=Gbobject.objects.get(title=i)
print 'The Object created was',gd
#Decsription
try:
atv=package_description_dict[i]
atvalue=unicode(atv,'utf-8')
except UnicodeDecodeError:
pass
try:
lo=Gbobject.objects.get(title=i)
loid=NID.objects.get(id=lo.id)
except Gbobject.DoesNotExist:
pass
if atvalue<>'':
slu=slugify(atvalue)
at=Attribute()
at.title=atvalue
at.slug=slu
at.svalue=atvalue
at.subject=loid
att=Attributetype.objects.get(title='Description')
at.attributetype=att
#with reversion.create_revision():
at.save()
print 'yeloow13'
Run Code Online (Sandbox Code Playgroud)
就像Description,有大约2个属性的包,以类似的方式保存.
这是发生错误时获得的完整回溯: -
error Traceback (most recent call last)
/home/radhika/Desktop/dev_75/gnowsys-studio/demo/<ipython console> in <module>()
/usr/local/lib/python2.6/dist-packages/django_gstudio-0.3.dev-py2.6.egg/gstudio/Harvest/debdata.py in …Run Code Online (Sandbox Code Playgroud) class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
cmd = [ "bash", 'process.sh']
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
print ("-- " + line.rstrip())
print "Exiting " + self.name
def stop(self):
print "Trying to stop thread "
self.run = False
thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()
Run Code Online (Sandbox Code Playgroud)
所以我有如上所示的线程,实际上在windows上工作,process.sh是在cygwin中运行的bash脚本,需要大约5分钟才能完成执行所以它不是一个循环它的一些模拟proecess
我想在这个类中创建stop()函数,以便我可以在需要时立即终止脚本.终止后,我不希望process.sh脚本有任何有用的结果
请你建议任何方法,如果可能的话请给出一点解释..
python multithreading subprocess python-multithreading python-2.7
我使用的是Python 2.7.我有一个计时器,它一直重复计时器回调操作,直到它被停止.它使用Timer对象.问题是在它停止后,它无法重新启动.Timer对象代码如下;
from threading import Timer
class RepeatingTimer(object):
def __init__(self,interval, function, *args, **kwargs):
super(RepeatingTimer, self).__init__()
self.args = args
self.kwargs = kwargs
self.function = function
self.interval = interval
def start(self):
self.callback()
def stop(self):
self.interval = False
def callback(self):
if self.interval:
self.function(*self.args, **self.kwargs)
Timer(self.interval, self.callback, ).start()
Run Code Online (Sandbox Code Playgroud)
要启动计时器,请运行以下代码;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()
Run Code Online (Sandbox Code Playgroud)
要停止计时器,代码是;
repeat_timer.stop()
Run Code Online (Sandbox Code Playgroud)
停止后,我尝试通过调用重新启动计时器,repeat_timer.start()但计时器无法启动.定时器如何在停止后重新启动?
谢谢.
在单独的线程中调用相同函数的最佳方法是什么,并且每个实例都有一个单独的列表,其中包含返回值,而不重复函数?
例:
import threading
def function(a):
returned_values = []
ct = threading.currentThread()
while getattr(ct, "do_run", True):
ret = do_something(a)
returned_values.append(ret)
t1 = threading.Thread(target=function, args=("AAA",))
t2 = threading.Thread(target=function, args=("BBB",))
t3 = threading.Thread(target=function, args=("CCC",))
t1.start()
t2.start()
t3.start()
import time;time.sleep(10)
t1.do_run = t2.do_run = t3.do_run = False
Run Code Online (Sandbox Code Playgroud)
编辑:忘记提到我使用Python 2.7
如果我在守护程序线程中有以下代码,而主线程没有在守护程序上调用联接。一旦主线程退出或不退出,文件是否会在“ with”内部使用而安全关闭?无论如何要使其安全?感谢:D
while True:
with open('file.txt', 'r') as f:
cfg = f.readlines()
time.sleep(60)
Run Code Online (Sandbox Code Playgroud) python daemon with-statement python-multithreading python-2.7
考虑以下程序。
import asyncio
import multiprocessing
from multiprocessing import Queue
from concurrent.futures.thread import ThreadPoolExecutor
import sys
def main():
executor = ThreadPoolExecutor()
loop = asyncio.get_event_loop()
# comment the following line and the shutdown will work smoothly
asyncio.ensure_future(print_some(executor))
try:
loop.run_forever()
except KeyboardInterrupt:
print("shutting down")
executor.shutdown()
loop.stop()
loop.close()
sys.exit()
async def print_some(executor):
print("Waiting...Hit CTRL+C to abort")
queue = Queue()
loop = asyncio.get_event_loop()
some = await loop.run_in_executor(executor, queue.get)
print(some)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我只想在按“ CTRL + C”时正常关机。但是,执行程序线程似乎阻止了该操作(即使我确实致电shutdown)
如果我看到如下的堆栈跟踪:
Exception in thread Thread-101:
Traceback (most recent call last):
(...)
Run Code Online (Sandbox Code Playgroud)
“线程101”是否必然意味着有101个活动/打开/性能下降的线程?还是这些名称像数据库中的ID一样工作,即使删除(关闭)了较旧的记录(线程),该数字也始终会上升?