【问题标题】:Converting the command line python code to normal python script without command line将命令行 python 代码转换为没有命令行的普通 python 脚本
【发布时间】:2020-08-31 20:11:50
【问题描述】:

我有以下从命令行获取输入的代码。我想在 streamlit 中运行此代码,而不是从命令行获取参数的值,而是将它们设置为一些默认值,例如“-i”,我希望它默认打开相机。我怎样才能做到这一点?

def build_argparser():
    parser = ArgumentParser()

    general = parser.add_argument_group('General')
    general.add_argument('-i', '--input', metavar="PATH", default='0',
                         help="(optional) Path to the input video " \
                         "('0' for the camera, default)")
    general.add_argument('-o', '--output', metavar="PATH", default="",
                         help="(optional) Path to save the output video to")
    general.add_argument('--no_show', action='store_true',
                         help="(optional) Do not display output")
    general.add_argument('-tl', '--timelapse', action='store_true',
                         help="(optional) Auto-pause after each frame")
    general.add_argument('-cw', '--crop_width', default=0, type=int,
                         help="(optional) Crop the input stream to this width " \
                         "(default: no crop). Both -cw and -ch parameters " \
                         "should be specified to use crop.")
    general.add_argument('-ch', '--crop_height', default=0, type=int,
                         help="(optional) Crop the input stream to this height " \
                         "(default: no crop). Both -cw and -ch parameters " \
                         "should be specified to use crop.")
    general.add_argument('--match_algo', default='HUNGARIAN', choices=MATCH_ALGO,
                         help="(optional)algorithm for face matching(default: %(default)s)")

【问题讨论】:

  • 您是只想运行脚本名称而没有其他内容,还是希望在运行脚本时指定标志并希望这些标志默认运行某些操作?
  • 我不想在运行脚本时指定标志。我想默认设置所有的标志。
  • 如果您不需要任何命令行参数,则不要使用任何命令行参数。只需在脚本中定义所有路径和引用。另外,如果您使用的是相机,请查看 opencv 库,它可以帮助您运行和更改视频帧。

标签: python command-line-arguments streamlit


【解决方案1】:

见:https://docs.python.org/3/library/argparse.html#the-parse-args-method

通常我们会这样做:

parser = argparse.ArgumentParser()
# ... define what to expect
arg = parser.parse_args()

arg 将是参数对象,它是从sys.argv 解析的,这是您在命令行中输入的。也可以将字符串列表放入函数中,如

arg = parser.parse_args(["--match_algo", "-ch"])

上面的链接有更多示例,说明您可以使用的参数的不同变体。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多