要查看Python程序是否在运行,您可以使用以下方法:
使用命令行工具:
`ps -ef | grep python`:列出所有包含“python”的进程。
`top` 或 `htop`:按CPU使用率排序,找到Python进程。
`pgrep python`:列出所有Python进程的PID。
使用Python库:
`psutil`:这是一个跨平台的库,可以检索进程和系统信息。
import psutil
def check_process_running(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if 'python' in proc.info['name']:
return True
return False
使用文件记录:
创建一个文件来记录进程ID,然后检查该文件是否存在,或者检查记录的文件中的进程ID是否在运行。
import os
import psutil
def write_pid():
pid = os.getpid()
with open('pid.log', 'w') as f:
f.write(str(pid))
def read_pid():
if os.path.exists('pid.log'):
with open('pid.log', 'r') as f:
return f.read()
return False
def check_run():
pid = int(read_pid())
if pid > 0 and pid in psutil.pids():
return True
return False
使用系统监视工具:
`tasklist`(Windows): 列出所有进程,并通过`IMAGENAME`过滤特定程序。
`WMI`(Windows): 使用`Win32_Process`查询特定进程是否存在。