[英]How to terminate/killall a program in python
Linux等效killall(ProgramName)的第一個簡單答案
該程序將是一個切換程序。 我可以啟動 Firefox/程序。 def tolaunch(program): os.system("firefox")
啟動時,我希望將啟動的程序的名稱保存在數組中(做起來很簡單),然后啟動程序(Firefox)/程序。
切換開關的想法出現了,當啟動並且我完成瀏覽時,我希望調用相同的程序(我的),檢查所述程序的數組並退出 Firefox/程序,通過運行一個簡單的命令,如 killall(“ Firefox”)但在 Python 代碼中。 我不想寫一個冗長的命令/腳本,首先必須鍛煉'pid'。
我似乎非常接近答案,但找不到。
編輯:人們要求提供代碼示例 | 這是我的代碼
# Toggler for macro key -|- many keys = one toggler program
import os
import sys
def startp(program):
# hard-coded
os.system("firefox")
def exitp(program):
# os.close(program)
sys.exit(program)
# Begin
# hard-coded : program start
startp("Firefox")
# loop while program/s active
# exitp("Firefox")
# exit(program) or program end
我試圖在評論中加入一些解釋
您正在尋找的是sys.exit()
命令。
有 4 個函數可以退出程序。 它們是 quit()、exit()、sys.exit() 和 os._exit()。 它們具有幾乎相同的功能,因為它們引發了 SystemExit 異常,Python 解釋器通過該異常退出並且沒有在屏幕上打印堆棧回溯。
在上述四個退出函數中,sys.exit() 是首選,因為 exit() 和 quit() 函數不能在生產代碼中使用,而 os._exit() 僅適用於需要立即退出的特殊情況。
要使用 sys.exit() function 演示此行為:
import sys
i=0
while i in range(10):
i += 1
print(i)
if i == 5:
print('I will now exit')
sys.exit()
elif i > 5:
print('I will not run, program alredy exited :(')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.