![](/img/trans.png)
[英]Python writing dataframe to excel - Check if tab exists and overwrite otherwise create
[英]Check if existing process exists - if it does, communicate with it, otherwise create a new one
我確定以前有人問過這個問題,但我找不到了。
我寫了一個 Python 程序,給定一個目錄,它使用一個非常簡單的啟發式方法來確定如何“解壓”它的內容以及到什么目標目錄。
只要新的下載完成,就會執行此程序。 如果很多下載幾乎同時完成,我會得到很多同時解包的進程。 我想通過重寫程序的大部分來一次只解壓一個目錄來解決這個問題。
因此,為了實現這一點,我想我會使用一個“鎖/PID”文件,其中包含任何當前正在執行的程序的 PID。 如果鎖/PID 文件存在,新生成的進程應該簡單地向現有進程發送類似("queue", "D:/some/directory")
的內容,並讓該進程在完成其目標后解壓縮該目標當前開箱。
我將如何在 Python 中實現這一目標? 這必須適用於 Windows 系統,但理想情況下也適用於 GNU/Linux。
如果你只是想檢查PID文件是否存在,你可以使用: os.path
os.path.exists(path)
所以既然你已經在使用像Ben Finney 的 lockfile這樣的東西
例子:
from lockfile.pidlockfile import PIDLockFile
lock = PIDLockFile('somefile')
lock.acquire(timeout=3600)
#do stuff
lock.release()
您可能想要與正在運行的守護進程通信,您應該讓守護進程監聽某個套接字,然后從生成的進程將數據發送到套接字。 (例如 udp 套接字)
所以在守護進程中:
import socket
import traceback
import Queue
import threading
import sys
hostname = 'localhost'
port = 12368
#your lockfile magick here
# if you want one script to run each time, put client code here instead of seperate script
#if already running somehwere:
#message = "hello"
#sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
#sock.sendto( message, (hostname, port) )
#sys.exit(0)
que = Queue.Queue(0)
socket_ = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_.bind((hostname, port))
class MyThread(threading.Thread):
def run(self):
while True: #maybe add some timeout here, so this process closes after a while
# but only stop if que.empty()
message = que.get()
print "handling message: %s" % message
#handle message
t = MyThread()
t.start()
while True:
try:
#blocking call
message, _ = socket_.recvfrom(8192) #buffer size
print "received message: %s" % message
#queue message
que.put(message)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
在客戶端:
import socket
hostname = 'localhost'
port = 12368
message = "hello"
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.sendto( message, (hostname, port) )
如果您在同一台機器上運行所有這些,則可以使用“localhost”作為主機名。
另一方面,使用多進程管道而不是 sockets 可能是正確的方法,但我還沒有使用它們的經驗。 這種設置的額外好處是能夠在不同的機器上運行服務器和客戶端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.