要判断Python程序是否正在运行,您可以使用以下方法:
1. 使用`psutil`库:
import psutil
def check_process_running(process_name):
for proc in psutil.process_iter(['name']):
if proc.info['name'] == process_name:
return True
return False
if check_process_running('python'):
print('Python is running.')
else:
print('Python is not running.')
2. 使用`tasklist`命令(仅限Windows系统):
import os
import subprocess
def check_python_process():
result = subprocess.run('tasklist | findstr python', shell=True, stdout=subprocess.PIPE)
if result.returncode == 0:
return True
return False
if check_python_process():
print('Python is running.')
else:
print('Python is not running.')
3. 使用`ps`命令(Linux系统):
import subprocess
def check_python_process():
result = subprocess.run('ps -ef | grep python', shell=True, stdout=subprocess.PIPE)
if result.stdout.strip():
return True
return False
if check_python_process():
print('Python is running.')
else:
print('Python is not running.')
4. 使用`pgrep`命令(Linux系统):
import subprocess
def check_python_process():
result = subprocess.run('pgrep python', shell=True, stdout=subprocess.PIPE)
if result.stdout.strip():
return True
return False
if check_python_process():
print('Python is running.')
else:
print('Python is not running.')
请选择适合您操作系统的方法进行使用