我有一个每天都必须运行的 python 文件,因此我正在制作一个批处理文件,用于自动执行此过程。问题是:这个 python 脚本中有一个输入函数。我必须每天运行它,按“1”,“输入”,就是这样。
我已经学会了
python_location\python.exe python_script_location\test.py
我可以运行该脚本。但是,我不知道如何将“1”传递给运行上述批处理代码时触发的输入函数。
我已经尝试过echo 1 | python_location\python.exe python_script_location\test.py
它给了我一个“EOF”错误。
最佳答案
这里有一些解决方案。这个想法是编写一段代码来检查是否需要从用户或设置变量获取输入。
解决方案1:
使用命令行参数设置输入变量。
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)
如果手动运行,则不带参数执行
$ python3 script.py
Manual input: 1
1
如果从批处理文件运行,请使用参数执行
$ python3 script.py --some_var=1
Auto input: 1
1
解决方案2
使用环境变量设置输入变量。
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)
如果手动运行,则不加环境变量执行
$ python3 script.py
Manual input: 1
1
如果从批处理文件运行,请使用环境变量执行
$ export some_var=1
$ python3 script.py
Auto input: 1
1
关于python - 从批处理文件运行 python 脚本时,如何自动将输入值传递给 python "input"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69010439/