代码之家  ›  专栏  ›  技术社区  ›  Helena

如何通过Python3将多个带值的参数传递给可执行文件?

  •  0
  • Helena  · 技术社区  · 3 年前

    我正在尝试通过python3运行windows可执行文件,下面是代码片段。参数的形式可以是 key-value 但可能很少有参数没有这样的值 arg1 在下面 arg2 需要有一个在创建时传递的值 arg2 变量如下。数据。需要使用文件路径来构造arg2

     # data.filepath resolves to \\server1\data\inputs\filename.txt
     arg2 = "--arg2 {}".format(data.filepath)  
    child = subprocess.Popen([output_path, "--arg1", arg2, "--arg3 val3", "--arg4 val4"],
                             shell=False, stderr=subprocess.STDOUT)
    child.communicate()[0]
    rc = child.returncode
    

    但似乎我没有遵循正确的语法,并得到如下错误

    Throw location unknown (consider using BOOST_THROW_EXCEPTION)
    Dynamic exception type: class boost::exception_detail::clone_impl<struct boost::exception_detail::error_info_injector<class boost::program_options::unknown_option> >
    std::exception::what: unrecognised option '--arg2 \\server1\data\inputs\filename.txt'
    

    请告诉我python中正确的语法,以便正确地将参数传递给可执行文件。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Ture Pålsson    3 年前

    显然,您正在运行的程序希望收到一个参数及其值作为单独的字符串(这很有意义)。你可以这样做

    if phase_of_moon() == 'waxing gibbous':
        arg2 = ['--arg2', data.filepath]
    else:
        arg2 = []
    x = Popen([output_path, '--arg1', *arg2, '--arg3', val3])
    

    使用 iterable unpacking 扩展 arg2 .