简体   繁体   中英

How to print output of python script to Windows console, when running via batch file?


I've been looking for an answer to this backwards and forwards but to no avail. I work on Windows and wrote a script in Python which copies a source files to other backup destinations (Dropbox folder and remote drive).

import os, shutil

source = r'C:\****\****\Accounts_Passes.kdbx'
file_name = source.split('\\')[-1]
cloud_backup = r'C:\****\Dropbox\Backup'
pendrive_backup = r'I:'

def backup (source, destination):
    if not os.path.exists(destination):
        os.mkdir(destination)
    shutil.copy(source, destination)



if __name__ == '__main__':
    if os.path.exists(pendrive_backup.split('\\')[0]):
        backup(source, pendrive_backup)
        print(f"{file_name} file backed up to pendrive!")
    else:
        print(f"Pendrive disconnected, couldn't backup {file_name} to it")
    backup(source, cloud_backup)
    print(f"{file_name} file backed up to Dropbox!")
    print("DONE!")

I want it to run it via Windows Task Scheduler so I created a.bat file.

echo off
echo Backup launched
timeout /t 5
start "C:\Program Files\Python38\python.exe" "C:\*****\Backup Scripts\Keypass_backup.py"
pause

The problem is when I run it via.bat file the output of the Python script doesn't show in the console which I would strongly demand. Any advice on how to make the command line opened via batch file, display the print outputs of the Python script would be great.

Thanks,
Mike

My advice is that you correct your batch file content.

You should get rid of start from line 4 of your provided content.

@Echo Backup launched
@%__AppDir__%timeout.exe /T 5 /NoBreak
@"%ProgramFiles%\Python38\python.exe" "C:\*****\Backup Scripts\Keypass_backup.py".
@Pause

If you wanted to ignore that advice and use start anyhow, then the correct syntax would be:

@Start "" "%ProgramFiles%\Python38\python.exe" "C:\*****\Backup Scripts\Keypass_backup.py".

Without that syntax, your start command was actually using C:\Program Files\Python38\python.exe as a 'Window Title', and running the command, "C:\*****\Backup Scripts\Keypass_backup.py" , which isn't what you wanted it to do.

If you open up a Command Prompt window, type either start /? or help start , and press ENTER , you should see that the first set of doublequotes is for defining the title.

Also, you should be able to run "C:\Program Files\Python38\python.exe" via the task scheduler, with "C:\*****\Backup Scripts\Keypass_backup.py" as an argument, without the need for a at all. You could probably even do that by running cmd.exe via the task scheduler, with /K , "C:\Program Files\Python38\python.exe" and "C:\*****\Backup Scripts\Keypass_backup.py" as its arguments too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM