![](/img/trans.png)
[英]subprocess.CalledProcessError When running robocopy from Python 3 on Windows 7
[英]Can't kill robocopy subprocess from python
在我windows的項目中,我想啟動兩個目錄的鏡像。
我知道我可以使用 python 看門狗來做到這一點,但我認為使用 robocopy 會更容易和更快。
為了簡化情況,假設我有一個帶有兩個按鈕的 GUI:啟動和停止鏡像。
以下是帶有相關代碼的片段:
class MirrorDemon(Thread):
def __init__(self, src, dest) :
self.threading_flag = Event()
self.src = src
self.dest = dest
self.opt = ' /MIR /MON:1 /MOT:1'
self.mirror = None
Thread.__init__(self)
def run(self):
command = 'robocopy {} {} {}'.format(str(self.src),str(self.dest), self.opt)
self.p = subprocess.Popen(command.split(), shell=True)
print(command)
print('start robocopy with PID {}'.format(self.p.pid))
class Window(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
def stop_demon(self):
self.mirror.threading_flag.set()
self.mirror.p.kill()
self.mirror.join()
print('stop demon')
def start_demon(self):
self.mirror = MirrorDemon(Path('./src'), Path('./dest'))
self.mirror.setDaemon(True)
self.mirror.start()
print('start demon')
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec())
當您單擊開始按鈕時,您會在控制台上打印出一個 PID,如果我在任務列表中檢查此 PID,它對應於“cmd.exe”進程,並且 robocopy 開始其工作。
點擊停止后,PID對應的cmd.exe進程消失,但后台robocopy還在繼續!!
我嘗試了幾種變體,但沒有運氣。
你有什么建議嗎? 您知道是否有人找到了解決方案嗎? 或者也許實施了鏡像看門狗?
謝謝
按照@Ulrich 的建議,設置 shell=False 實際上是在做技巧並殺死 robocopy 進程。
謝謝!
通過改變這個:
self.p = subprocess.Popen(command.split(), shell=True)
對此:
self.p = subprocess.Popen(command.split(), shell=False)
...您確保該進程將直接從當前進程啟動,而不啟動新的 shell 進程來啟動它。
您取回的 PID 是針對 shell 進程的,您可以終止 shell 而無需終止從該 shell 啟動的進程。通過不在新的 shell 中啟動它,您取回的 PID 是實際進程的 PID,並且你將能夠按預期殺死它。
正如文檔所述:“您唯一需要在 Windows 上指定shell=True
的時間是當您希望執行的命令內置於 shell(例如 dir 或 copy)時。您不需要shell=True
來運行批處理文件或基於控制台的可執行文件。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.