【问题标题】:How to automatically pass an input value to python "input" function, when running python script from batch file从批处理文件运行python脚本时,如何自动将输入值传递给python“输入”函数
【发布时间】:2021-10-30 18:14:07
【问题描述】:

我有这个 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”错误。

【问题讨论】:

    标签: python batch-file input echo


    【解决方案1】:

    这里有一些解决方案。这个想法是编写一段代码来检查它是否需要从用户或一组变量中获取输入。

    解决方案 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
    

    【讨论】:

    • 第二个没用,第一个完美!谢谢!
    猜你喜欢
    • 2019-01-04
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2013-09-29
    • 2010-10-24
    相关资源
    最近更新 更多