简体   繁体   English

查看python进程是否已在运行的最佳方法是什么?

[英]What is the best way to see if a python process is already running?

I'm trying to write a script that monitors my python program to see if it is already running. 我正在尝试编写一个脚本来监视我的python程序,以查看它是否已在运行。

I started by trying to assign this script to an object: 我首先尝试将此脚本分配给一个对象:

processWatch = os.system("sudo ps afxj | grep quickConversion.py")
if processWatch > 2:  #if more than one is running it won't run.
    while 1:
        "rest of loop"

I then tried to monitor the object for more than one instance. 然后,我尝试监视该对象的多个实例。

You may want to pay a look at psutils to handle processes. 您可能需要看一下psutils来处理进程。

import psutil

processWatch = [p.cmdline() for p in psutil.process_iter()].count(['python', 'quickConversion.py'])
if processWatch > 0:
    `while 1: `
        `"rest of loop"`

There are Linux commands that return a list of processes: 有一些Linux命令可返回进程列表:

if 'your_process' in commands.getoutput('ps -A'):
    print 'Your process in running.'

Subprocess's Popen is very useful for this. 子进程的Popen为此非常有用。 https://docs.python.org/3.4/library/subprocess.html https://docs.python.org/3.4/library/subprocess.html

import subprocess

process = subprocess.Popen(cmd)
if process.poll() is None:
    print("The process hasn't terminated yet.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中处理HTML的最佳方法是什么? - What's the best way to process HTML in Python? 在长时间运行的c进程和python之间进行双向IPC的最佳方法是什么? - what is the best way to do bidirectional IPC between a long-running c process and python? 查看 Python 中是否存在具有给定 pid 的进程的最简单方法是什么? - What is the easiest way to see if a process with a given pid exists in Python? 使用Python访问已运行的进程 - Accessing an ALREADY running process, with Python 用Python处理大量网络数据包的最佳方法是什么? - What is the best way to process large amount of network packets in Python? 使用 python 从进程中捕获输出的最佳方法是什么? - What is the best way to capture output from a process using python? Python,确定Unix进程是否正在运行的正确方法是什么? - Python, what is the correct way to determine if a Unix process is running? 在同一台计算机上运行的Python软件之间进行通信的最佳方式是什么? - What is the best way to communicate between Python softwares running on the same computer? 保持python循环运行直到被用户停止的最佳方法是什么? - What is the best way to keep a python loop running until stopped by the user? Python-将参数传递给已经运行的进程 - Python - Passing arguments to an already running process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM