【问题标题】:How can i pass python variable to a shell command [duplicate]我如何将python变量传递给shell命令[重复]
【发布时间】:2021-10-26 15:00:17
【问题描述】:

我有一个带有 webhost、用户名和密码变量的 python 脚本,我试图将其传递给同一个 python 脚本中的 shell 命令。

output = subprocess.check_output(['curl -s -G -u username:password -k \"https://webhost/something/something\"'], shell=True, encoding='utf-8')

你能帮我怎么做吗?我尝试了多种方法,但都没有奏效。

谢谢

【问题讨论】:

    标签: python python-3.x bash shell command-line-interface


    【解决方案1】:

    不要构造字符串供shell解析;只需提供一份清单。该列表可以直接包含字符串值变量(或从变量构造的字符串)。

    username = ...
    password = ...
    url = ...
    
    output = subprocess.check_output([
                    'curl',
                    '-s',
                    '-G',
                    '-u',
                    f'{username}:{password}',
                    '-k',
                    url
               ], encoding='utf-8')
    

    【讨论】:

      【解决方案2】:

      试试这个,

      username = 'abc'
      password = 'def'
      webhost = '1.2.3.4'
      
      output = subprocess.check_output([f'curl -s -G -u {username}:{password} -k \"https://{webhost}/something/something\"'], shell=True, encoding='utf-8')
      

      它被称为 f 字符串。 https://docs.python.org/3/tutorial/inputoutput.html

      在字符串开始之前添加一个 f,将要插入的变量括在花括号中。

      您可以使用这种语法将变量传递到字符串中。

      您也可以将变量作为列表传递,如下所示,命令中的每个参数都是一个单独的项目,您可以像这样在要解析的列表项目上使用 f 字符串,

      username = 'abc'
      password = 'def'
      webhost = '1.2.3.4'
      
      output = subprocess.check_output(['curl',
       '-s', 
       '-G',
       '-u',
       f'{username}:{password}',
       '-k',
       f'\"https://{webhost}/something/something\"'],
       encoding = 'utf-8')
      

      【讨论】:

      • 将字符串作为列表传递是一个错误;它恰好可以在 Windows 上运行,但确实应该产生警告。你想要subprocess.check_output(['curl', '-s', '-G', '-u', f'{username}:{password}', '-k', 'https://{webhost}/something/something'], encoding='utf-8'),这也避免了讨厌的shell=True
      • 我将编辑我的答案
      猜你喜欢
      • 2021-11-30
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 2014-10-06
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多