我想在主程序停止时停止Python线程。它用于连接到服务器的类。连接由后台线程维护,前台线程响应回调。以下是一个最小的示例。
#!/usr/bin/python
import time, threading
class test():
running = False
def __init__(self):
print "init"
self.running = True
self.thread = threading.Thread(target = self.startThread)
self.thread.start()
def __del__(self):
running = False
print "del"
def startThread(self):
print "thread start"
while self.running:
time.sleep(1)
print "thread running"
a = test()
Run Code Online (Sandbox Code Playgroud)
当程序结束时,我天真地期望调用 __del__() 以便通知后台线程停止,但直到后台线程停止后才调用 i。显式调用某些函数不是一个选项,因为该类已被其他人使用,我不想强迫他们使用一些额外的代码行。
我有以下代码使用threading并打印当前计数。
import threading
count = 0
def worker():
"""thread worker function"""
global count
count += 1
print(count)
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
Run Code Online (Sandbox Code Playgroud)
当前设置为 5 个线程。我怎样才能让它继续运行线程直到达到某个#。即以 5 个线程运行,直到worker()运行 100 次。
我有一个安装了 Python 3 的嵌入式系统(armv5tejl AT91SAM9X25,具有 128MB RAM,运行基于 buildroot 的 rootfs)。我已经让系统运行很多天了,我开始对其进行一些Python开发工作,但似乎在创建新线程时遇到了问题。
如果我尝试运行以下程序:
Type "help", "copyright", "credits" or "license" for more information.
>>> import threading
>>> import time
>>> def func():
... i = 0
... while True:
... i += 1
... print(i)
... time.sleep(1)
...
>>>
>>> func()
1
2
3
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in func
KeyboardInterrupt
>>> t = threading.Thread(target=func)
>>> t.start()
Traceback (most recent call last): …Run Code Online (Sandbox Code Playgroud) linux multithreading embedded-linux python-multithreading python-3.x
只是为了提供一些背景信息:我目前正在学习 Python,为此我启动了一个小项目。
我编写了两个 Python 脚本:主机脚本和客户端脚本。
我已经处于多个客户端可以连接到一个“主机”并且主机可以向所有客户端发送随机字符串的阶段。
现在我想解决这个问题,如果客户端与主机断开连接,直到再次调用 CLIENTSOCKET 之前没有人知道。
因此,我暂时编写了 checkConnection 方法,每 5 秒 ping 一次所有客户端。
class Connection():
def __init__(self):
self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def bound(self,RHOST,PORT):
self.s.bind((RHOST,PORT))
self.s.listen(1000)
def connect(self):
((CLIENTSOCKET,ADRESS)) = self.s.accept()
return (CLIENTSOCKET,ADRESS)
def newConnection(Connection,CLIENTS):
con = Connection
cli = CLIENTS
while True:
c = con.connect()
if c != None:
if len(cli) != 0:
for x in range (len(cli)):
if c[1][0] == cli[x][1][0]:
pass
else:
cli.append(c)
else:
cli.append(c)
def checkConnection(CLIENTS):
cli = CLIENTS
while True:
if(len(cli)!=0):
for x in …Run Code Online (Sandbox Code Playgroud) 我创建了一个简单的脚本,它遍历我需要 ping 和 nslookup 的服务器列表。问题是,ping 可能需要一些时间,尤其是 ping 比一天中的秒数更多的服务器。
我对编程相当陌生,我知道多处理或多线程可能是使我的工作运行得更快的解决方案。
我的计划是获取我的服务器列表和 1. 将它分成大小均匀的列表,列表的数量与线程/进程匹配,或者 2. 如果这些选项之一支持它,则遍历单个列表,每个列表都传递一个新的在完成之前的 ping 和 nslookup 后,线程或进程的服务器名称。这是可取的,因为它确保我花费最少的时间,就好像列表 1 有 200 个离线服务器而列表 6 有 2000 个,它需要等待使用列表 6 的过程完成,即使所有其他人在那个时候都是免费的观点。
哪一个更适合这项任务,为什么?
如果可能,我将如何确保每个线程或进程具有基本相同的运行时
代码片段即使现在相当简单
import subprocess
import time
server_file = open(r"myfilepath", "r")
initial_time = time.time()
for i in range(1000):
print(server_file.readline()[0:-1]+ ' '+str(subprocess.run('ping '+server_file.readline()[0:-1]).returncode)) #This returns a string with the server name, and return code,
print(time.time()-initial_time)
Run Code Online (Sandbox Code Playgroud)
出现此问题是因为每次失败的 ping 平均需要 3 秒以上。此外,我知道不放置打印语句会使它更快,但我想监视它的一个小案例。我正在对 100,000 台服务器的影响进行 ping 操作,这将需要定期执行,并且该列表将继续增长
python multithreading ping python-multithreading python-multiprocessing
我想在线程中调用一个函数。使用传统 API 调用它看起来像:
from threading import Thread
import numpy as np
a = np.random.rand(int(1e8),1)
Thread(target=np.savez_compressed, args=('/tmp/values.a', dict(a=a))).start()
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个 pythonic 是使用更干净的 API 进行这个线程调用,而不定义一个特定于np.savez_compressed.
例如(伪代码)风格的东西:
@make_threaded
np.savez_compressed('/tmp/values.a', dict(a=a))
Run Code Online (Sandbox Code Playgroud)
不幸的是,装饰器只能应用于函数定义,所以上面的伪代码是不合法的。
编辑:我不是专门寻找装饰器 API。相反,一种使函数调用线程化的更简洁的方法
我的请求是从调试器和 pycharm 提示符中获取调试数据:
假设我有一个带有错误的旧式 python 同步程序:
def listdir(self, remote_path):
with ssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
password=self.connection_settings['password']) as conn:
with conn.start_sftp_client() as sftp:
sftp.chdir(remote_path) # breakpoint here
files = sftp.readdir()
files_name = [file.filename for file in files]
return files_name
Run Code Online (Sandbox Code Playgroud)
我会停止它,转到调试器,单击调试器控制台-> 显示 python 提示,然后在运行时调试我的问题:
> sftp.getcwd()
bad_user_location
> sftp.chdir(good_base_location)
> sftp.readdir()
Run Code Online (Sandbox Code Playgroud)
只需即时重写代码并测试状态和运行时即可。(这一直是我调试的方式,使用immediate windowMicrosoft 语言开发中的,以及 Python 和其他脚本语言中的 REPL。
现在我有一个异步程序:
async def listdir(self, remote_path):
async with asyncssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
password=self.connection_settings['password']) as conn:
async with conn.start_sftp_client() as sftp:
await sftp.chdir(remote_path) # breakpoint here
files = await sftp.readdir() …Run Code Online (Sandbox Code Playgroud) python debugging asynchronous python-multithreading python-asyncio
我在网上经历了多种解决方案,但它们需要大量代码,一旦您扩展,这些代码可能会令人困惑。是否有一种简单的方法可以停止线程并避免RuntimeError: threads can only be started once, 以便无限次调用线程。这是我的代码的简单版本:
import tkinter
import time
import threading
def func():
entry.config(state='disabled')
label.configure(text="Standby for seconds")
time.sleep(3)
sum = 0
for i in range(int(entry.get())):
time.sleep(0.5)
sum = sum+i
label.configure(text=str(sum))
entry.config(state='normal')
mainwindow = tkinter.Tk()
mainwindow.title('Sum up to any number')
entry = tkinter.Entry(mainwindow)
entry.pack()
label = tkinter.Label(mainwindow, text = "Enter an integer",font=("Arial",33))
label.pack()
print(entry.get())
button = tkinter.Button(mainwindow, text="Press me", command=threading.Thread(target=func).start)
button.pack()
Run Code Online (Sandbox Code Playgroud) python multithreading tkinter software-design python-multithreading
我在正确使用代码时遇到了一些困难,因为在 VSCode 上调试时我的代码完成执行后出现以下错误:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000188AB3259D0>
Traceback (most recent call last):
File "c:\users\gam3p\appdata\local\programs\python\python38\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "c:\users\gam3p\appdata\local\programs\python\python38\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "c:\users\gam3p\appdata\local\programs\python\python38\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "c:\users\gam3p\appdata\local\programs\python\python38\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Run Code Online (Sandbox Code Playgroud)
如果我使用命令行运行代码,我也会收到以下错误:
Cancelling an overlapped future failed
future: <_OverlappedFuture pending overlapped=<pending, 0x25822633550> cb=[_ProactorReadPipeTransport._loop_reading()]>
Traceback (most recent call last):
File "c:\users\gam3p\appdata\local\programs\python\python38\lib\asyncio\windows_events.py", line 66, in _cancel_overlapped
self._ov.cancel()
OSError: [WinError 6] …Run Code Online (Sandbox Code Playgroud) python python-multithreading python-3.x python-asyncio visual-studio-code
下面是我逐行编写的代码(大约有900 页,每行 10 行和 5 个数据)有什么办法可以使它更快。目前将数据导出到 csv需要80 分钟。有什么方法可以对页面进行并行请求并提高此代码的效率。
import requests
from urllib3.exceptions import InsecureRequestWarning
import csv
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from bs4 import BeautifulSoup as bs
f = csv.writer(open('GEM.csv', 'w', newline=''))
f.writerow(['Bidnumber', 'Items', 'Quantitiy', 'Department', 'Enddate'])
def scrap_bid_data():
page_no = 1
while page_no < 910:
print('Hold on creating URL to fetch data...')
url = 'https://bidplus.gem.gov.in/bidlists?bidlists&page_no=' + str(page_no)
print('URL created: ' + url)
scraped_data = requests.get(url, verify=False)
soup_data = bs(scraped_data.text, 'lxml')
extracted_data = soup_data.find('div', {'id': 'pagi_content'})
if len(extracted_data) == 0: …Run Code Online (Sandbox Code Playgroud) python multithreading asynchronous threadpool python-multithreading
python ×9
python-3.x ×3
asynchronous ×2
debugging ×1
linux ×1
ping ×1
threadpool ×1
tkinter ×1