2

I have a main.py script that is using the module timeloop. I think this module is important in this case

then I have a launch.vbs file with the following content

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

I ran the launch.vbs

But now I cannot stop the script without restarting my Windows or taskkill /IM pythonw.exe /F

I want to do it in a more elegant way.

What I want to achieve

Minimum expectation:

  • I can find the running script in Task Manager and then end task from there.
  • create a cli tool that can stop this particular script.
  • Any thing similar to the two above mentioned points. More expectation
  • my script will appear here and I can exit it from here.right side of taskbar

My script:

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)

More info

When my code runs after 40 seconds as in the code above, a python icon appears in the box that is in the image I showed earlier. and then it suddenly goes away. It comes and goes way every 40 seconds just like that.

user692942
  • 16,398
  • 7
  • 76
  • 175
Curious Learner
  • 1,182
  • 1
  • 4
  • 17
  • Please note that I have seen most of the similar content in stack overflow. But could not find a specific solution. So please don't mark it as duplicate. Then I have to post it again. – Curious Learner Oct 30 '21 at 06:03

0 Answers0