【问题标题】:How to check if a python script is still running from another python script如何检查 python 脚本是否仍在从另一个 python 脚本运行
【发布时间】:2021-04-10 05:25:49
【问题描述】:

所以基本上我有一个脚本,可以从我的网络服务器下载 python 文件然后运行它们。我现在正在寻找一种方法来检测下载的 python 脚本是否已完成运行,因为我希望原始 python 脚本再次运行以下载下一个文件等等。我试图在没有用户输入的情况下完全自动化地做到这一点。我试图通过检查文本文件是否已更改来做到这一点,但我意识到这将要求任何尝试上传其代码的用户在其代码中添加文件更改功能。

这是我的一些代码供参考:

import time

import wget
import os
import requests

def lookForFile():
    oldNumber=len(os.listdir("./upload"))
    while True:
        time.sleep(20)
        NumberOfFiles = len(os.listdir("./upload"))
        if NumberOfFiles != oldNumber:
            os.system('python ./upload/1.py')
            oldNumber = NumberOfFiles
def isRunning():
    file = "save.txt"
    with open(file) as f:
        lines = f.readlines()
        print(lines)
def notRunning():
    f = open("save.txt", "w")
    f.write("NotRunning")
    f.close()

    # open and read the file after the appending:
    f = open("save.txt", "r")
    print(f.read())

def updateRobot():
    url = "url/1.py"

    response = requests.get(url)
    angel = response.json()
    print(angel["currentNumber"])


def downloadScript():
    url = "url/1.py"

    wget.download(url, './upload/')

def main():
    pass

【问题讨论】:

  • 您使用的是哪个操作系统?您可以使用 pgrep -lf 查看它是否正在运行。或者使用subprocess.run 运行你的脚本,这将阻塞直到它完成,而不是 os.system()
  • 我目前正在 Windows pc 上测试它,但计划在我的树莓派上运行它
  • 其实 os.system 也会阻塞。那么你的问题是什么?

标签: python


【解决方案1】:

您是否尝试过使用subprocess.run()

请参阅下面的示例,了解它的阻塞性质。这样您就可以直接处理文件而无需经常检查。

我有两个文件:

  1. sleep_for_10_seconds.py
import time
time.sleep(10)
  1. call_using_subprocess.py
import subprocess
import time

file_to_run = 'sleep_for_10_seconds.py'
cmd_to_run = ['python', file_to_run]

before_running = time.time()
print(f'Current epoch: {before_running}')

subprocess.run(cmd_to_run)

print(f'Time elapsed since running: {time.time() - before_running}')

运行 call_using_subprocess 给我以下输出:

Current epoch: 1618035414.6788576
Time elapsed since running: 10.054320335388184

【讨论】:

    【解决方案2】:

    我认为这将满足您的要求。它列出了脚本启动时已经存在的所有 python 进程 PID。然后每秒检查当前正在运行的不在该列表中的 python 进程。然后,您可以在其中一个进程离开该列表时添加回调,例如我放置“完成”打印语句的位置。

    import time
    import psutil
    import threading
    
    
    background_processes = [p.pid for p in psutil.process_iter() if 'python' in p.name()]
    
    
    def find_nonbackground_processes():
        processes = []
        for p in psutil.process_iter():
            if 'python' in p.name():
                if p.pid not in background_processes:
                    processes.append(p.pid)
        return processes
    
    
    def wait_for_changes():
        processes = find_nonbackground_processes()
        print(processes)
        while True:
            current = find_nonbackground_processes()
            print(current)
            for p in processes:
                if p not in current:
                    print(p, ' is done!')
            processes = current
            time.sleep(1)
    
            
    t = threading.Thread(target=wait_for_changes)
    t.start()
    

    当它运行时,如果我在后台启动然后停止一个 ipython 进程,我会得到以下打印语句:

    []
    []
    []
    [14204, 15008]
    [14204, 15008]
    []
    14204  is done!
    15008  is done!
    []
    []
    

    PS 这似乎与Check if python script running from another python script linux 相似,但可能完全不同,因此我写了这个更具体的答案。

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 2017-03-30
      • 2023-03-20
      相关资源
      最近更新 更多