1.查看python進程
在Windws中查看python進程,在 shell 中执行如下指令:
wmic process where name="python.exe"
或者
wmic process where name="python.exe" list full
2. Python啟動python文件
os.popen() 方法用于从一个命令打开一个管道。
os.popen()方法格式如下:
os.popen(command[, mode[, bufsize]])
參數:
- command--使用的命令。
- model--模式權限可以是'r'(默認)或'w'。
- bufsize--指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。
3. 查看程序是否在運行
import os, re
def start_python_module(module_name):
# 查看所有運行的python程序
python_full = os.popen("wmic process where name='python.exe' list full").readlines()
# 正則查找python程序是否在已運行的python程序中
com = re.compile(module_name)
ret = com.search(''.join(python_full))
# 發現程序未運行,執行啟動命令
if not ret:
os.popen("python %s" % module_name)
print("python 程序啟動完成")
# 發現程序已經在運行中,不執行啟動命令
else:
print("python 程序已啟動")
if __name__ == '__main__':
# python程序名
module_name = 'processing.py'
start_python_module(module_name)
4. 通過Apscheduler設置定時查看程序是否在運行
import os, re
from apscheduler.schedulers.blocking import BlockingScheduler
module_name = 'tmp.py'
def start_python_module():
# 查看所有運行的python程序
python_full = os.popen("wmic process where name='python.exe' list full").readlines()
# 正則查找python程序是否在已運行的python程序中
com = re.compile(module_name)
ret = com.search(''.join(python_full))
# 發現程序未運行,執行啟動命令
if not ret:
os.popen("python %s" % module_name)
print("python 程序啟動完成")
# 發現程序已經在運行中,不執行啟動命令
else:
print("python 程序已啟動")
# 每天start_time啟動程序
def start1(start_time):
assert len(start_time.replace(':', '')) == 4, "請輸入正確的時間"
scheduler = BlockingScheduler()
scheduler.add_job(start_python_module, 'cron', hour=start_time[:2], minute=start_time[2:])
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
# 每過time秒啟動一次
def start2(time):
assert isinstance(time, int), "輸入錯誤"
scheduler = BlockingScheduler()
scheduler.add_job(start_python_module, 'interval', seconds=time)
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
# start_time = '09:24'
# start1(start_time)
start2(1)