Home > other >  How to automatically pass an input value to python "input" function, when running python s
How to automatically pass an input value to python "input" function, when running python s

Time:09-17

I have this python file that I have to run everyday, so I'm making a batch file that I'll use to automate this process. The thing is: this python script has an input function in it. I have to everyday run it, press "1", "enter", and that's it.

I've learned that with

python_location\python.exe python_script_location\test.py

I can run the script. I don't know, however, how to pass "1" to the input function that is triggered when I run the aforementioned batch code.

I've tried echo 1 | python_location\python.exe python_script_location\test.py and it gives me an 'EOF' error.

CodePudding user response:

Here are some solutions. The idea is to write a piece of code that will check whether it needs to get the input from the user or from a set variable.

Solution 1:

Using command line arguments to set the input variable.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--some_var', default=None, required=False)
cli_args = parser.parse_args()

def get_input(var_name):
    if auto_input := getattr(cli_args, var_name, None):
        print("Auto input:", auto_input)
        return auto_input
    else:
        return input("Manual input: ")

some_var = get_input("some_var")
print(some_var)

If running manually, execute without arguments

$ python3 script.py 
Manual input: 1
1

If running from a batch file, execute with arguments

$ python3 script.py --some_var=1
Auto input: 1
1

Solution 2

Using environment variables to set the input variable.

import os

def get_input(var_name):
    if auto_input := os.getenv(var_name):
        print("Auto input:", auto_input)
        return auto_input
    else:
        return input("Manual input: ")

some_var = get_input("some_var")
print(some_var)

If running manually, execute without the environment variable

$ python3 script.py 
Manual input: 1
1

If running from a batch file, execute with the environment variable

$ export some_var=1
$ python3 script.py 
Auto input: 1
1
  • Related