在windows中:双击运行Python程序、后台运行Python程序
在windows中:雙擊運行Python程序、后臺運行Python程序
安裝Python解釋器的windows環境,如果雙擊運行*.py的文件,會閃退。怎樣避免閃退呢?
我們用python的日志輸出程序來舉例說明:
main.py中
import os
import logging
import time
# 如果日志文件夾不存在,則創建
log_dir = "log" # 日志存放文件夾名稱
log_path = os.getcwd() + os.sep + log_dir
if not os.path.isdir(log_path):
os.makedirs(log_path)
# 設置logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
main_log_handler = logging.FileHandler(
log_dir + "/dd_%s.log" % time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(time.time())), mode="w+",
encoding="utf-8")
main_log_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
main_log_handler.setFormatter(formatter)
logger.addHandler(main_log_handler)
# 控制臺打印輸出日志
console = logging.StreamHandler() # 定義一個StreamHandler,將INFO級別或更高的日志信息打印到標準錯誤,并將其添加到當前的日志處理對象
console.setLevel(logging.INFO) # 設置要打印日志的等級,低于這一等級,不會打印
formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
while True:
time_stamp = time.time()
# print("時間戳",time_stamp)
logger.info("時間戳 %s" % time_stamp)
sec = 3
logger.info("睡眠 %s 秒" % sec)
time.sleep(sec)
一、雙擊運行python的具體實現
1、bat啟動
start_show.bat 中(.bat文件 必須放在main.py的同一目錄下)
python main.py
2、升級版:vbs后臺運行(無界面)
start_hidden.vbs 中(.vbs 文件必須放在main.py的同一目錄下,且必須有 .bat 文件同在)
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c start_show.bat",0
二、windows中怎么快捷殺掉Python程序?
答:bat殺
stop_all_python.bat 中 (會殺死所有的Python程序)
taskkill /IM python.exe /F
三、其他說明:
1、帶界面雙擊啟動
雙擊start_show.bat
會出現cmd窗口,同時會產生日志文件夾
2、不帶界面后臺運行程序
雙擊start_hidden.vbs
進程會增加一個python.exe進程,增加的python.exe進程為后臺啟動的,可以通過日志查看
3、殺死所有Python.exe進程
雙擊stop_all_python.bat
所有的Python進程都消失了,第1部中產生的cmd窗口也消失了。
==========================我是一條優美的分割線==========================
擴展:答復網友MR_Mason
一、問題:
二、答復:
1、思路
windows下的:taskkill /IM python.exe /F 命令會將所有python解釋器進程全部殺死。
windows下的:taskkill /pid 1235404 /f 命令會將進程編號為1235404的進程殺死。那么我們要做的就是找到main.py啟動時的進程編號,然后在寫入到名為stop_main.bat文件中,形如:
taskkill /pid 1235404 /f del %0
注意:
pid后面的進程號是python程序隨機生成的,所有獲取pid進程號的時候也必須用python程序自動獲取。
del %0 命令的作用是stop_main.bat文件運行結束后,刪除stop_main.bat文件。目的是防止反復雙擊運行stop_main.bat文件,誤刪系統進程,導致系統崩潰。
2、實現
將main.py增加如下代碼
# ========增加代碼--開始========
def produce_stop_bat(pid, tmpfile="stop_xxx.bat"):
# 待寫入內容
stop_cmd = 'taskkill /pid ' + str(pid) + ' /f' # 關閉指定進程
del_self_cmd = "del %0" # 刪除自身文件
# 文件路徑和名稱
tmp_all = "stop_" + tmpfile + ".bat"
# 寫入文件
with open(file=tmp_all, mode="w") as f:
f.write(stop_cmd + "
" + del_self_cmd)
# 進程號
pid = os.getpid()
# 本文件名(不含后綴.py)
myfilename = os.path.split(__file__)[-1].split(".")[0]
# 生成關閉進程的腳本文件
produce_stop_bat(pid, myfilename)
# ========增加代碼--結束========
增加代碼后,完整的main.py
import os
import logging
import time
# ========增加代碼--開始========
def produce_stop_bat(pid, tmpfile="stop_xxx.bat"):
# 待寫入內容
stop_cmd = 'taskkill /pid ' + str(pid) + ' /f' # 關閉指定進程
del_self_cmd = "del %0" # 刪除自身文件
# 文件路徑和名稱
tmp_all = "stop_" + tmpfile + ".bat"
# 寫入文件
with open(file=tmp_all, mode="w") as f:
f.write(stop_cmd + "
" + del_self_cmd)
# 進程號
pid = os.getpid()
# 本文件名(不含后綴.py)
myfilename = os.path.split(__file__)[-1].split(".")[0]
# 生成關閉進程的腳本文件
produce_stop_bat(pid, myfilename)
# ========增加代碼--結束========
# 如果日志文件夾不存在,則創建
log_dir = "log" # 日志存放文件夾名稱
log_path = os.getcwd() + os.sep + log_dir
if not os.path.isdir(log_path):
os.makedirs(log_path)
# 設置logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
main_log_handler = logging.FileHandler(
log_dir + "/dd_%s.log" % time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(time.time())), mode="w+",
encoding="utf-8")
main_log_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
main_log_handler.setFormatter(formatter)
logger.addHandler(main_log_handler)
# 控制臺打印輸出日志
console = logging.StreamHandler() # 定義一個StreamHandler,將INFO級別或更高的日志信息打印到標準錯誤,并將其添加到當前的日志處理對象
console.setLevel(logging.INFO) # 設置要打印日志的等級,低于這一等級,不會打印
formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
while True:
time_stamp = time.time()
# print("時間戳",time_stamp)
logger.info("時間戳 %s" % time_stamp)
sec = 3
logger.info("睡眠 %s 秒" % sec)
time.sleep(sec)
3、效果展示
(1)運行前
(2)雙擊start_show.bat(或者雙擊 start_hidden.vbs),運行后
(3)結束main進程
說明:進程查詢的方式詳見分割線之前部分。
如果有用,請給個贊唄!!!多謝。(^_^)
能力擴展:bat、dos控制多個后臺程序啟動
https://www.cnblogs.com/andy9468/p/12603877.html
總結
以上是生活随笔為你收集整理的在windows中:双击运行Python程序、后台运行Python程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Code Issues 2,637 Pu
- 下一篇: 使用代码自动打开ABAP Editor