标签: python-multithreading

如何在 Python 中的单独线程中启动 win32 应用程序

所以,我有以下代码片段,它试图通过 win32api 启动 Microsoft Powerpoint:

import threading
import win32com.client
import sys

class myDemo(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        try:
            myObject = win32com.client.Dispatch("Powerpoint.Application")
            print "OK"
        except:
            print "Failed to start Powerpoint!"
            sys.exit(1)            
        print "Now attempting to shutdown..."
        try:
            myObject.quit()
        except:
            print "Error"


if __name__ == "__main__":
    test = myDemo()
    test.start()
Run Code Online (Sandbox Code Playgroud)

问题是它失败了,我不知道为什么。但是,如果我将最后一行更改为test.run()它将成功启动。那么,为什么这会失败test.start()?

为什么会发生这种情况,考虑到我需要 Powerpoint 在单独的线程上异步运行,我应该如何解决它?

提前致谢。

编辑:显然我的问题与此有关:http : //python.6.x6.nabble.com/Dispatch-error-CoInitialize-has-not-been- called-td1951088.html

然而,除了提出的正确解决方案之外,似乎没有人回答为什么 COM 会以这种方式行事。

python winapi pywin32 win32com python-multithreading

2
推荐指数
1
解决办法
5007
查看次数

Python 多处理帮助条件退出

我正在用 Python 进行多处理,但我对这个主题没有任何运气。基本上我有一个运行起来很耗时的程序。我需要在 1 到 100 的范围内运行它,但是一旦满足我正在寻找的条件,我想中止所有进程。条件是返回值 == 90。

这是一个非多进程代码块。谁能给我一个例子,说明他们如何将其转换为多进程函数,一旦满足“90”条件,代码将退出所有进程?

def Addsomething(i):
    SumOfSomething = i + 1    
    return SumOfSomething

def RunMyProcess():
    for i in range(100):
        Something = Addsomething(i)
        print Something
    return

if __name__ == "__main__":
    RunMyProcess()
Run Code Online (Sandbox Code Playgroud)

编辑:

我在测试第三个版本时遇到了这个错误。知道是什么原因造成的吗?

Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 554, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 507, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Python27\lib\multiprocessing\pool.py", line 379, in _handle_results
    cache[job]._set(i, obj)
  File "C:\Python27\lib\multiprocessing\pool.py", line 527, in _set
    self._callback(self._value)
  File "N:\PV\_Proposals\2013\ESS - …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing multiprocess python-multithreading

2
推荐指数
1
解决办法
3832
查看次数

如何在多线程python程序中使用PostgreSQL

我在多线程 python 程序中使用 psycopg2 (2.6) 连接到 PostgreSQL 数据库。

当程序中的队列大小增加时,选择查询会得到错误“没有要获取的结果”,但将记录插入数据库效果很好。

示例代码:

class Decoders(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        self.decode()

    def decode(self):
        queue = self.queue
        db = Database()
        while queue.qsize() > 0:    
            # calling db methods, just an example
            temp = queue.get()
            db.select_records()
            db.insert_record(temp)
Run Code Online (Sandbox Code Playgroud)

和:

Decoders(queue).start()
Decoders(queue).start()
Run Code Online (Sandbox Code Playgroud)

注意:我在多处理方面没有这个问题。

编辑:

当我只启动一个线程时,程序没有任何问题。

数据库类:

class Database:
    db = object
    cursor = object

    def __init__(self):
        self.db = connect(host=conf_hostname,
                          database=conf_dbname,
                          user=conf_dbuser,
                          password=conf_dbpass,
                          port=conf_dbport)
        self.db.autocommit = True
        self.cursor = self.db.cursor()

    def select_records(self):
        self.cursor.execute(simple select) …
Run Code Online (Sandbox Code Playgroud)

python multithreading psycopg2 python-multithreading

2
推荐指数
1
解决办法
9498
查看次数

queue.get() 只返回一项

我正在构建一个小嗅探器来接收我网络中设备的答案。我宁愿通过实现answers()Scapys Packet 类的方法来解决这个问题,但这并没有按预期工作。我试图通过首先创建一个嗅探线程,然后将数据包发送到设备并等待答案来绕过它。

import threading
from scapy.all import sniff
class SnifferThread(threading.Thread):

    """ Thread that sniffs for incoming packets
    """

    def __init__(self, queue, timeout=1, checkFunction=None, filter=None):
        """ Initialization method """
        if queue is None:
            raise Exception, "queue must not be None"

        self.q = queue
        self.filter = filter
        self.timeout = timeout
        self.checkFunction = checkFunction

        threading.Thread.__init__(self)


    def putInQueue(self, packet):
        """ Checks packet and puts it into the queue if it matches """
        if self.checkFunction:
            if self.checkFunction(packet):
                self.q.put(packet)
                print "put"
        else:
            self.q.put(packet) …
Run Code Online (Sandbox Code Playgroud)

python queue scapy python-multithreading

2
推荐指数
1
解决办法
1800
查看次数

python线程以最好的方式终止或终止

问题是我想杀死当前正在运行的所有线程。例如,我有一个调用 for 循环的按钮。突然间我想阻止它。

这是我的代码:

class WorkerThread(threading.Thread):
    def __init__(self,t,*args):
        super(WorkerThread,self).__init__(target=t,args=(args[0],args[3]))
        self.start()
        self.join()
Run Code Online (Sandbox Code Playgroud)

我的实现:

def running(fileopen,methodRun):
    #....long task of code are here...


for file in fileTarget:
        threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
Run Code Online (Sandbox Code Playgroud)

python python-multithreading

2
推荐指数
1
解决办法
1万
查看次数

何时使用线程以及使用多少线程

我有一个工作项目。我们已经编写了一个模块,并在那里作为#TODO 来实现线程以改进模块。我是一个相当新的 Python 程序员,并决定尝试一下。在学习和实现线程时,我遇到了类似于多少线程太多的问题?因为我们有一个大约需要处理 6 个对象的队列,那么为什么在处理时间可以忽略不计的情况下创建 6 个线程(或任何线程)来处理列表或队列中的对象呢?(每个对象最多需要大约 2 秒来处理)

所以我做了一个小实验。我想知道使用线程是否有性能提升。请参阅下面的我的python代码:

import threading
import queue
import math
import time

results_total = []
results_calculation = []
results_threads = []

class MyThread(threading.Thread):
    def __init__(self, thread_id, q):
        threading.Thread.__init__(self)
        self.threadID = thread_id
        self.q = q

    def run(self):
        # print("Starting " + self.name)
        process_data(self.q)
        # print("Exiting " + self.name)


def process_data(q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            potentially_prime = True
            data = q.get()
            queueLock.release()
            # check if the data is …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-multithreading

2
推荐指数
1
解决办法
9268
查看次数

如何在python中的正在运行的线程中更改参数值

如何更改在线程(python)中无限循环运行的函数的参数?我是线程和 python 的新手,但这就是我想要做的(简化),

class myThread (threading.Thread):
   def __init__(self, i):
       threading.Thread.__init__(self)

   def run(i):
       self.blink(i)

   def blink(i):   
       if i!=0:
           if i==1:
               speed=0.10
           elif i==2:
               speed=0.20
           elif i==3:
               speed=0.30    

           while(true):
               print("speed\n")

i=3
blinkThread=myThread(i)
blinkThread.start()

while(i!=0):
i=input("Enter 0 to Exit or 1/2/3 to continue\n")
if i!=0:
   blinkThread.run(i)
Run Code Online (Sandbox Code Playgroud)

现在,很明显这段代码给出了关于 run() 方法的错误。我想在无限循环中运行函数blink() 但更改'i' 变量。没有线程我也无法完成,因为我还有其他部分代码在执行并行任务。我能做什么?谢谢!

python multithreading python-multithreading

2
推荐指数
1
解决办法
8027
查看次数

没有返回值的多处理池?

我正在尝试使用Pool没有返回值的多处理进行并行计算。如果不需要从子流程返回和检索值,它可能会更快。有没有办法做到这一点?

这是一个简单的例子:

from multiprocessing import Pool

def fun(a):
    # do something.. 
    a["1"]=100

a={
   "1":12
   }
multi = [a] * 10
p = Pool(4)
p.map(fun, multi)
data = [a["1"] for a in multi]
print(data)
>>> [12, 12, 12, 12, 12, 12, 12, 12, 12, 12]

[fun(a) for a in multi]
data = [a["1"] for a in multi]
print(data)
>>> [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
Run Code Online (Sandbox Code Playgroud)

有人知道为什么吗?有解决方案吗?

python multiprocessing python-multithreading python-3.x

2
推荐指数
1
解决办法
3589
查看次数

Python从无限循环线程返回值

因此,对于我的程序,我需要检查本地网络上的客户端,该客户端运行着 Flask 服务器。这个 Flask 服务器正在返回一个可以改变的数字。

现在为了检索该值,我使用了请求库和 BeautifulSoup。
我想在脚本的另一部分使用检索到的值(同时不断检查其他客户端)。为此,我想我可以使用线程模块。
然而,问题是线程只在循环完成后才返回它的值,但循环需要是无限的。

这是我到目前为止得到的:

import threading
import requests
from bs4 import BeautifulSoup

def checkClient():
    while True:
        page = requests.get('http://192.168.1.25/8080')
        soup = BeautifulSoup(page.text, 'html.parser')
        value = soup.find('div', class_='valueDecibel')
        print(value)

t1 = threading.Thread(target=checkClient, name=checkClient)
t1.start()
Run Code Online (Sandbox Code Playgroud)


有谁知道如何将打印的值返回给另一个函数?当然,您可以用某种 API 替换 requests.get url,其中值变化很大。

python infinite-loop while-loop python-multithreading python-3.x

2
推荐指数
1
解决办法
2118
查看次数

为什么在所有期货完成后与 futures.as_completed 一起使用时 concurrent.futures 执行程序映射会抛出错误?

我正在尝试并发发送 HTTP 请求。为此,我使用了concurrent.futures

这是简单的代码:

import requests
from concurrent import futures

data = range(10)


def send_request(item):
    requests.get("https://httpbin.org/ip")
    print("Request {} complete.".format(item))


executor = futures.ThreadPoolExecutor(max_workers=25)

futures_ = executor.map(send_request, data)

for f in futures.as_completed(futures_):
    f.result()
Run Code Online (Sandbox Code Playgroud)

如果我运行它,我可以看到请求是异步发送的,这正是我想要做的。但是,当所有请求都完成时,我收到以下错误:

Request 0 complete.
Request 6 complete.
...
Request 7 complete.
Request 9 complete.
Request 3 complete.
Traceback (most recent call last):
  File "send_thread.py", line 18, in <module>
    for f in futures.as_completed(futures_):
  File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 219, in as_completed
    with _AcquireFutures(fs):
  File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 146, in __enter__
    future._condition.acquire()
AttributeError: …
Run Code Online (Sandbox Code Playgroud)

python concurrency python-multithreading python-3.x

2
推荐指数
1
解决办法
4021
查看次数