简体   繁体   English

检查Python脚本是否正在运行

[英]Check a Python Script Is Running

I have a python script named update.py, and I want to use another python script to check whether the script is running or not. 我有一个名为update.py的python脚本,我想使用另一个python脚本来检查该脚本是否正在运行。 If update.py doesn't run or error, then the script will run update.py. 如果update.py没有运行或出错,则脚本将运行update.py。

Can i do it? 我可以做吗? If there is an example it will be very thankful. 如果有一个例子,将非常感激。

Scripts are generally used for these kinds of tasks. 脚本通常用于此类任务。 You have a monitor script that keeps track of update.py that keeps running in the background. 您有一个监视脚本,该脚本跟踪在后台运行的update.py。 It becomes easier if monitor script launches the python script in the beginning. 如果监视脚本在开始时启动python脚本,将变得更加容易。

#!/bin/bash
# Monitor script. 

EXEC=<path>/update.py

while true; do
    "$EXEC" &
    wait # Here the assumption is that you want to run this forever. 
done

Not sure about what you are asking but as given this may help, so if you just want to call one python script from another then you can use script 1 不确定您要问的是什么,但是鉴于此可能有所帮助,因此,如果您只想从另一个调用一个python脚本,则可以使用脚本1

 #!/usr/bin/python 
 from subprocess import call
 call(["python", "update.py"])

Save this file in a script named script1 and run it, it will compile update.py. 将此文件保存在名为script1的脚本中并运行,它将编译update.py。 If you want to check for any syntax error in update.py then you can use script 2 如果要检查update.py中是否存在语法错误,则可以使用脚本2

#!/usr/bin/python
from subprocess import call
call(["python","-m","py_compile", "update.py"])

If script2 compiles without any error then it shows that there is no syntax error in your program. 如果script2编译时没有任何错误,则表明程序中没有语法错误。

Thirdly if you want to check if update.py is running currently or not you can use script 3 第三,如果要检查update.py当前是否正在运行,可以使用脚本3

#!/usr/bin/python
import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'update.py']:
         sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'update.py'])

This last script will tell if your script is running or not and if it is not running it will compile it. 最后一个脚本将告诉您脚本是否正在运行,如果未运行,则会对其进行编译。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM