简体   繁体   中英

Is there a way to have Windows task scheduler automatically respond to input() in Python script?

I'm trying to schedule a python script to run automatically on a Windows 10 machine. The script, when run alone, prompts the user for some input to use as it runs. I'd like to automatically set these inputs when the scheduler runs the .bat file. As an example:

test.py :

def main():
    name = input('What is your name? ')
    print(f'Hello, {name}. How are you today?')

main()

This works fine if I just run the script, but ideally I'd like to have the name variable passed to it from the .bat file.

test.bat :

"path\to\python.exe" "path\to\test.py"
pause

Any help would be greatly appreciated!

If you just want to give a single fixed input, you can do it like:

REM If you add extra spaces before `|` those will be passed to the program
ECHO name_for_python| "path\to\python.exe" "path\to\test.py"

Unfortunately, there is no good way of extending this to multiple lines. You would use a file containing the lines you want to input for that:

"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt

If you want to have everything into a standalone script, you may do something like this:

REM Choose some path for a temporary file
SET temp_file=%TEMP%\input_for_my_script
REM Write input lines to file, use > for first line to make sure file is cleared
ECHO input line 1> %temp_file%
REM Use >> for remaining lines to append to file
ECHO input line 2>> %temp_file%
ECHO input line 3>> %temp_file%
REM Call program with input file
"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt
REM Delete the temporary file
DEL %temp_file% /q

Obviously, this is assuming you cannot use the standard sys.argv (or extensions like argparse ), which would be the more standard and convenient way to send arguments to a script.

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