Python 在一段时间后挂起,按 [Enter] 时继续

Jay*_*shi 7 python powershell

我制作了一个 python 脚本,它每 2 秒打印和记录一次特定进程的 CPU % 和内存使用情况。

它工作得很好。直到我去休息。(一小时后)当我再次检查时,python 脚本已暂停(或挂起)。当我按下 [Enter] 时,它又像往常一样开始执行。该脚本工作正常 1 小时。然后日志和输出丢失了 1 小时 30 分钟,而不是再次正常工作。

暂停的原因是什么。?

我怎样才能防止它。?

重要笔记:

  • 我正在使用 RDP(远程桌面)的机器上工作。但是连接仍然在一个小时后正常运行。
  • VM 的操作系统为:Windows Server 2016。
  • 在命令提示符中运行脚本。
  • “logger.txt”中没有错误。
  • 我正在监控 powershell.exe
  • 当我监视除 powershell.exe 之外的任何其他进程时,脚本不会挂起(我使用 python.exe 和 taskmgr.exe 进行了测试)
  • powershell 进程肯定在运行。我检查了 Powershell 脚本的日志,它一直在运行。

全码:

import psutil
import re
import math
import traceback
from time import ctime,sleep,localtime,time
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

import sys

def logg(msg):
    msg_parsed = str(ctime()) + " : " + str(msg)
    with open("logger.txt","a") as ff:
        ff.write("\n" + msg_parsed)

def aprint(msg, process="", counter = "" , pos=0,size=90):
    def sprint(msg):
        if not pos:
            print(msg)
        elif pos==1:
            print("|" + msg[0:size] + " "*(size- (len(msg[0:size]))) + "|" + " "*size+"|")
        elif pos==2:
            print("|"  + " "*size+"|" + msg[0:size] + " "*(size- (len(msg[0:size]))) + "|")


    msg = str(ctime()) + " : " + str(process) + " : " + counter + " : " + str(msg)
    sprint(msg)
    if counter or process:
        f = open("_".join((counter.replace(" ",""), process.replace(" ",""))) +".log", "a")
    else:
        f = open("perf.log", "a")
    f.write(msg+"\n")
    f.close()

    try:
        res = requests.post("https://localhost:8088/services/collector", headers={"Authorization": "Splunk 1b61f1eb-e29f-4d29-9f70-b7f88bcd5b65"}, data='{"time": %d , "index":"main","sourcetype": "FIFA:%s", "event":"%s"}' % (time(),counter,msg), verify = False)
        if "Success" not in res.text:
            sprint("[WARNING]")
            logg(" WARNING : " + res.text)

    except Exception as eee:
        sprint("[ERROR]")
        logg(msg + " ::: coulld not sent :::" + str(eee))
        logg(traceback.print_exc())


def convert_size(size_bytes):
   if size_bytes == 0:
       return "0B"
   size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
   i = int(math.floor(math.log(size_bytes, 1024)))
   p = math.pow(1024, i)
   s = round(size_bytes / p, 2)
   return "%s %s" % (s, size_name[i])


while True: 
    try:
        rrs =0
        cpptime = 0
        leave = False
        matched = None
        for proc in psutil.process_iter():
            if re.match(sys.argv[1].lower(),proc.name().lower()):
                leave = True
                matched = proc.name()
                rrs = max(rrs, proc.memory_info().rss)
                cpptime = max(proc.cpu_percent()/psutil.cpu_count(), cpptime)
        if matched:
            aprint( convert_size(rrs), matched ,"Memory" , pos=1)
            aprint( cpptime , matched ,"CPU", pos=2)

        try:
            sleep(2)

        except:
            break
    except Exception as ee:
        print(" [ERROR] :  " + str(ee))
        logg(ee)
        logg(traceback.print_exc())
Run Code Online (Sandbox Code Playgroud)

运行:python file.py <process name> 例如:python file.py python

日志文件:

Mon Jun 18 12:46:30 2018 : powershell.exe : memory : 2.29 GB
Mon Jun 18 12:46:33 2018 : powershell.exe : memory : 2.29 GB
Mon Jun 18 12:46:37 2018 : powershell.exe : memory : 2.29 GB
Mon Jun 18 12:46:40 2018 : powershell.exe : memory : 2.29 GB
Mon Jun 18 12:46:43 2018 : powershell.exe : memory : 2.29 GB
Mon Jun 18 12:46:46 2018 : powershell.exe : memory : 2.3 GB
Mon Jun 18 12:46:49 2018 : powershell.exe : memory : 2.3 GB
Mon Jun 18 12:46:53 2018 : powershell.exe : memory : 2.3 GB
Mon Jun 18 12:46:56 2018 : powershell.exe : memory : 2.3 GB
Mon Jun 18 12:46:59 2018 : powershell.exe : memory : 2.31 GB
Mon Jun 18 14:17:33 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:38 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:41 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:44 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:47 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:50 2018 : powershell.exe : memory : 3.11 GB
Mon Jun 18 14:17:53 2018 : powershell.exe : memory : 3.11 GB
Run Code Online (Sandbox Code Playgroud)

设置: 在此处输入图片说明

sta*_*tor 6

我使用以下最小示例来重现您的问题:

import time
while True:
    print(time.ctime())
    time.sleep(2)
Run Code Online (Sandbox Code Playgroud)

它只是每两秒打印一次时间。我使用以下命令从 cmd 运行此脚本:

python test.py
Run Code Online (Sandbox Code Playgroud)

唯一停止脚本的事情是当我点击进入控制台并进入“选择”模式以突出显示并从中复制文本时。所以也许你只是在休息时不小心点击了 cmd。您可以通过重定向输出来防止这种行为。在 cmd 中使用它:

python test.py > out.log 2> err.log
Run Code Online (Sandbox Code Playgroud)

或者在 PowerShell 中:

python test.py
Run Code Online (Sandbox Code Playgroud)

重定向输出和错误流。像这样调用python,进入选择模式将不再暂停脚本的执行。在这两个控制台中,您仍然可以随时按 CTRL+C 终止脚本(因此它不是后台进程,这也是一个解决方案)。