要判断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.')
请选择适合您操作系统的方法进行使用
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/142357.html