我正在嘗試撰寫一個類,其中包含一個無限回圈的方法,直到發出如下所示的顯式中斷請求:
# module_2
import sys
from time import sleep
from pathlib import Path
class Receiver:
def __init__(self, *args, **kwargs):
self.identified = False
self.id_= hex(id(self))
@property
def get_id(self):
self.identified = True
return self.id_
def write_id(self):
self.identified = True
with open('active_listeners.lst', 'a') as f:
f.write(str(self.id_))
return True
def _is_interrupted(self):
flag = Path.cwd().joinpath(Path(f'{self.id_}.interrupt'))
if flag.exists():
flag.unlink()
return True
return False
def listen(self):
if not self.identified:
print("can't start listening without identification or else can't stop listening.")
print("use 'get_id' or 'write_id' to identify me.")
return False
while True:
try:
print('listening...')
sleep(5)
result = 'foo'
print(f'got result: {result}')
with open(f'results_{self.id_}.tmp', 'w') as f:
f.write(result)
if self._is_interrupted():
sys.exit(0)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
r = Receiver()
r.write_id()
r.listen()
接收器既可以作為獨立物件執行,也可以通過將其匯入另一個模塊(如 module_1)來使用。
我這里有兩個問題,
在呼叫 Receiver.listen() 時,通過將 Receiver 匯入另一個模塊(比如 main)而不暫停 main 模塊的代碼執行流程來使用 Receiver 的最佳方法是什么?(聽是 I/O 系結,我在 Windows 上)
使用 Receiver 的最佳方法是什么而不顯式匯入它,而是從主模塊啟動 module_2 作為一個完全獨立的行程,就像在 Windows 上的單獨 shell 中執行“python -m module_2”一樣。在此使用中,我需要外殼保持打開狀態以監視輸出并停止使用“ctrl c”進行偵聽
uj5u.com熱心網友回復:
- 在執行緒中運行它,就像它作為主運行時所做的那樣:
from pathlib import Path
from threading import Thread
from module2 import Receiver
r = Receiver()
r.write_id()
t = Thread(target=r.listen)
t.start()
#do some other stuff...
#Path.cwd().joinpath(Path(f'{r.id_}.interrupt'))
#shorter way to write this:
flag = Path.cwd() / f'{r.id_}.interrupt'
with open(flag, 'w'): #"touch" your stopflag
pass
t.join() #wait for the thread to exit
keyboardinterrupt在這種情況下使用是不好的做法,因為它可以通過呼叫sys.exit(0). 通常圖書館不應該exit自己呼叫。始終讓主腳本這樣做。最好簡單地break從回圈中,讓函式回傳執行到任何啟動它的地方。如果它在自己的行程中,當函式回傳時,它將到達檔案的末尾并自行退出。
- 使用自己的 cmd 視窗將其作為自己的主腳本運行的一種簡單方法是使用呼叫“start”命令
os.system(如果您在另一個作業系統上運行,則此命令必須更改)。
from sys import argv
from time import sleep
import os
if __name__ == "__main__":
if '-child' not in argv: #don't fork bomb yourself...
cmd = f"start cmd /k python \"{__file__}\" -child"
#/k will keep the window open after the script completes
#/c will close immediately after completion
os.system(cmd)
for i in range(10): #just a simple example to demonstrate starting a new window...
print(i)
sleep(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369692.html
上一篇:在BASH中隨機排列命令串列?
