1

我有一个main.py使用模块的脚本timeloop。我认为这个模块在这种情况下很重要

然后我有一个包含以下内容的launch.vbs文件

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "pythonw D:\\PythonDevelopment\\desktop_cleaner\\main.py"

我跑了launch.vbs

但现在我无法在不重新启动Windowstaskkill /IM pythonw.exe /F

我想以更优雅的方式来做。

我想要达到的目标

最低期望:

  • 我可以在任务管理器中找到正在运行的脚本,然后end task从那里找到。
  • 创建一个cli tool可以停止此特定脚本的。
  • 任何类似于上述两点的事情。更多期待
  • 我的脚本将出现在这里,我可以从这里退出。任务栏右侧

我的脚本:

import time, os, os.path as path, win32api, logging, shutil
from win10toast import ToastNotifier
from timeloop import Timeloop
from datetime import timedelta

tl = Timeloop()
toast = ToastNotifier()
logging.basicConfig(
    filename="D:\\PythonDevelopment\\desktop_cleaner\\app.log",
    level=logging.DEBUG,
    format="[%(asctime)s - %(levelname)s]:  %(message)s",
    datefmt="%d-%b-%y %H:%M:%S",
)


def initial_check():
    """Checks if all conditions are satisfied to start cleaning process. If condtions are not met, it tries to setup all the required conditions."""
    report = {}
    desktop = path.expanduser("~\Desktop")
    desktop_store = path.expanduser("~\desktop_store")
    if path.exists(desktop) and path.isdir(desktop):
        logging.info("Located desktop directory at {}".format(desktop))
        report["desktop"] = desktop
        report["proceed"] = True
    else:
        logging.error("Cannot found desktop directory at {}".format(desktop))
        report["desktop"] = None
        report["proceed"] = False
    if path.exists(desktop_store) and path.isdir(desktop_store):
        logging.info("Located `desktop_store` directory at {}".format(desktop_store))
        report["desktop_store"] = desktop_store
    else:
        logging.error("`desktop_store` does not exist at {}".format(desktop))
        os.makedirs(desktop_store)
        report["desktop_store"] = desktop_store
        logging.info("`desktop_store` directory created")

    return report


def content_mover(src: str, dest: str):
    """moves all content from one directory to another"""
    src_content = os.listdir(src)
    rejected = []
    cannotmove = []
    logging.info(f"Content in the directory to be cleaned:- {src_content}")
    for item in src_content:
        if (
            os.path.splitext(item)[1] == ".lnk"
            or os.path.splitext(item)[1] == ".ini"
            or "Zoom background" in item
            or "Recycle Bin" in item
        ):
            rejected.append(item)
        else:
            try:
                shutil.move(os.path.join(src, item), dest)
            except shutil.Error as err:
                print(err)
                logging.error(str(err))
                if "already exists" in str(err):
                    cannotmove.append(item)
    if len(rejected) != 0:
        logging.warning(f"Items rejected before cleaning started:- {rejected}")
    if len(cannotmove) != 0:
        logging.warning(f"Items that already exists in desktop_store:- {cannotmove}")


@tl.job(interval=timedelta(seconds=40))
def main_desktop_cleaner():
    """This function gets called at an interval of 3 hours. Other required functions gets called inside this"""
    logging.info(
        f"======================NEW SESSION<{time.ctime()}>======================"
    )
    toast.show_toast(
        "Desktop Cleaner", "Desktop Cleaner started at {}".format(time.ctime())
    )
    initial_report = initial_check()
    if initial_report["proceed"]:
        logging.info("Ready to begin cleaning process")
        initial_report[
            "desktop"
        ] = "D:\\PythonDevelopment\\cleaner"  # temporary desktop alternative
        content_mover(initial_report["desktop"], initial_report["desktop_store"])
    else:
        logging.error("Proceed clearance failed")
        toast.show_toast(
            "Desktop Cleaner", "Required conditions were not met. Cleaning stopped."
        )


if __name__ == "__main__":
    main_desktop_cleaner()
    tl.start(block=True)

更多信息

当我的代码在上面的代码中运行 40 秒后,python 图标出现在我之前显示的图像中的框中。然后它突然消失了。就像那样,它每 40 秒来来去去。

4

0 回答 0