我想打開3個Powershell並在其中的3個文件中運行相同的代碼,只是不同的文件。
因爲他們將有完全相同的邏輯,他們每個人都會試圖訪問彼此的文件,以檢查是否有寫有什麼
處理1具有client1.txt,過程2具有client2.txt和Process3已client3.txt
下面是一些代碼爲應選擇工作這問題之前檢查什麼過程3:僅當沒有其他「進程」正在處理文件時纔讀取文件
import os
while True:
f = 'C:\Users\Files'
i = {}
i['word'] = 'problem X' #just an example, I'll have a whole list
if os.path.exists(f):
try:
os.rename(f, f)
print 'Access on file "' + f +'" is available!'
file1 = open('C:\Users\Files\client1.txt', 'r+')
file2 = open('C:\Users\Files\client2.txt', 'r+')
if file1.read() == i['word']:
print "A process is already working on this problem, check another"
elif file2.read() == i['word']:
print "A process is already working on this problem, check another"
else:
print "Found a new problem to work on"
file3 = open('C:\Users\Files\client3.txt', 'r+')
file3.write(i['word'])
file1.close()
file2.close()
file3.close()
except OSError as e:
print 'Access-error on file "' + f + '"! \n' + str(e)
time.sleep(5)
pass
我試圖通過代碼來表示就是:我只想要一個過程,如果別人是無法啓動的問題因爲他們都有相同的邏輯,他們會嘗試解決同樣的問題(我有很多需要解決的問題),所以他們可能會在程序的同一時間到達繼續與while True
。
當它完成問題時,它會刪除文件的內容並選擇一個新問題,然後將其正在處理的問題寫入其自己的文件中,供其他人稍後檢查。我們假設process1發現首先工作的問題('AAA'),它們都有空的txt文件,它會檢查txt2和txt3,並且看到它不等於('AAA '),然後它將它寫入它自己的文件並關閉它。
我想要process2,它可能會在第二秒後讀取txt1和txt3,並看到('AAA')已在使用中,它將獲得列表中的下一個並再次檢查,看到(' BBB')沒問題,它會寫在自己的文件上。
當它結束時,它從txt刪除字符串並開始尋找另一個字符串。
存在兩個進程都試圖同時檢查文件的問題。也許如果有一種方法可以將time.sleep()
添加到進程中(如果另一個進程正在使用該文件,然後稍後再試一次)?
沒有重複,但可能相關:https://stackoverflow.com/questions/30407352/how-to-prevent-a-race-condition-when-multiple-processes-attempt-to -write-to-and – paisanco
@paisanco我只理解一般的想法,因爲我是python的新手,但它非常有趣。你是否認爲他們提到的塊阻止了我想要的那種過程,或者只是線程/多進程和有'鏈接'的東西? – Tax