Pyinstaller使用--noconsole闪烁CMD窗口

时间:2018-08-21 21:40:50

标签: python python-2.7 pyinstaller

我有一个脚本,该脚本使用CPU负载来动态确定计算机应处于节能模式还是高性能模式。

这是整个脚本:

import os, os.path
import sys
import psutil
import subprocess


def subprocess_args(include_stdout=True):
    # The following is true only on Windows.
    if hasattr(subprocess, 'STARTUPINFO'):
        # On Windows, subprocess calls will pop up a command window by default
        # when run from Pyinstaller with the ``--noconsole`` option. Avoid this
        # distraction.
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        # Windows doesn't search the path by default. Pass it an environment so
        # it will.
        env = os.environ
    else:
        si = None
        env = None


    if include_stdout:
        ret = {'stdout': subprocess.PIPE}
    else:
        ret = {}


    ret.update({'stdin': subprocess.PIPE,
                'stderr': subprocess.PIPE,
                'startupinfo': si,
                'env': env })
    return ret

# A simple test routine. Compare this output when run by Python, Pyinstaller,
# and Pyinstaller ``--noconsole``.
if __name__ == '__main__':
    # Save the output from invoking Python to a text file. This is the only
    # option when running with ``--noconsole``.
    with open('out.txt', 'w') as f:
        try:
            txt = subprocess.check_output(['python', '--help'],
                                          **subprocess_args(False))
            f.write(txt)
        except OSError as e:
            f.write('Failed: ' + str(e))

# subprocess.Popen("A:\\Python27\\Scripts\\dist\\auto2.exe", close_fds=True)
# """ Now my python code can exit, and no nothing of itself will remain lingering """


while True:

    CPUload = (psutil.cpu_percent(interval=4))
    RAMload = (psutil.virtual_memory().percent)

    os.system('cls')

    print("CPU Load: {}%".format(CPUload))
    print("RAM Load: {}%".format(RAMload))

    # planlist = subprocess.check_output(["powercfg", "/list"], shell=False, stderr=subprocess.PIPE, stdin=subprocess.PIPE).split('\n')
    planlist = subprocess.check_output(["powercfg", "/list"], shell=False, **subprocess_args(False)).split('\n')    # Both of these lines seem to give the same result

    firstplan = planlist[3]
    secondplan = planlist[4]
    thirdplan = planlist[5]

    firstplanID = firstplan.split(": ")[1].split("  (")[0]
    secondplanID = secondplan.split(": ")[1].split("  (")[0]
    thirdplanID = thirdplan.split(": ")[1].split("  (")[0]

    activeplan = subprocess.check_output(["powercfg", "/getactivescheme"], shell=False, **subprocess_args(False))

    activeplanNAME = activeplan.split("(")[1].split(")")[0]
    firstplanNAME = firstplan.split("(")[1].split(")")[0]
    secondplanNAME = secondplan.split("(")[1].split(")")[0]
    thirdplanNAME = thirdplan.split("(")[1].split(")")[0]

    if "High performance" in firstplanNAME:
        HighPerformance = firstplanNAME
        HighPerformanceID = firstplanID

    if "High performance" in secondplanNAME:
        HighPerformance = secondplanNAME
        HighPerformanceID = secondplanID

    if "High performance" in thirdplanNAME:
        HighPerformance = thirdplanNAME
        HighPerformanceID = thirdplanID

    if "Power saver" in firstplanNAME:
        PowerSaver = firstplanNAME
        PowerSaverID = firstplanID

    if "Power saver" in secondplanNAME:
        PowerSaver = secondplanNAME
        PowerSaverID = secondplanID

    if "Power saver" in thirdplanNAME:
        PowerSaver = thirdplanNAME
        PowerSaverID = thirdplanID

    if activeplanNAME == PowerSaver:
        print("Active plan: Power saver")
    else:
        if activeplanNAME == HighPerformance:
            print("Active plan: High Performance")
        else:
            subprocess.call(["powercfg", "/s", HighPerformanceID], shell=False, **subprocess_args(False))

    if CPUload < 44:
        if RAMload > 90:
            if activeplanNAME == PowerSaver:
                subprocess.call(["powercfg", "/s", HighPerformanceID], shell=False, **subprocess_args(False))
                print("Switching to High Performance by RAM load...")

    if CPUload < 44:
        if RAMload < 90:
            if activeplanNAME == HighPerformance:
                subprocess.call(["powercfg", "/s", PowerSaverID], shell=False, **subprocess_args(False))
                print("Switching to Power saver...")

    if CPUload > 55:
        if activeplanNAME == PowerSaver:
            subprocess.call(["powercfg", "/s", HighPerformanceID], shell=False, **subprocess_args(False))
            print("Switching to High Performance...")

脚本本身可以正常工作,但是当使用pyinstaller --noconsole --onefile scriptname.py放入Pyinstaller时,该exe将在后台运行,然后刷新命令窗口,然后在后台运行,然后定期再次刷新。

感谢您的帮助。

0 个答案:

没有答案