【问题标题】:Python3 Using Variables from Python in os.popen() statement (WINDOWS)Python3 在 os.popen() 语句中使用 Python 中的变量(WINDOWS)
【发布时间】:2019-02-27 17:58:35
【问题描述】:

我正面临以下问题。 我正在使用 python3 构建一个小型卸载 Java 工具。

我可以读出我需要的所有内容,但是当我尝试将卸载命令发送到 Windows 时,我无法正确完成解析。

搜索已安装软件的命令如下:

wmic_output = os.popen('''wmic product where "name like 'Java 8 Update %%'" get name''').read()

os.popen 字符串中没有任何变量,一切正常。现在尝试执行命令似乎更棘手......

    productname = str(uninstallcall[inx])
    # Check if Version is installed, if so uninstall
    wmic_output1 = os.popen('''wmic product where "name like '%s'" get name''').read()
    result1 = parse_wmic_output(wmic_output1 % (productname))

是的,这样做时 productname 变量打印得很好:/

用于解析 Im 使用此处找到的以下片段 http://autosqa.com/2016/03/18/how-to-parse-wmic-output-with-python/

def parse_wmic_output(text):
    result = []
    # remove empty lines
    lines = [s for s in text.splitlines() if s.strip()]
    # No Instance(s) Available
    if len(lines) == 0:
        return result
    header_line = lines[0]
    # Find headers and their positions
    headers = re.findall('\S+\s+|\S$', header_line)
    pos = [0]
    for header in headers:
        pos.append(pos[-1] + len(header))
    for i in range(len(headers)):
        headers[i] = headers[i].strip()
    # Parse each entries
    for r in range(1, len(lines)):
        row = {}
        for i in range(len(pos)-1):
            row[headers[i]] = lines[r][pos[i]:pos[i+1]].strip()
        result.append(row)
    return result

【问题讨论】:

  • %s,您是否要在该位置插入变量?如果是这样,你需要做"some %s variable" % variable_to_inser。或者更简洁的方式,使用f"some {productname} here"f 在字符串的开头很重要)。
  • 确实如此。我试图在%s 所在的位置添加一个变量。你提供的选项已经回答了我的问题:) 坦克你:)

标签: python windows python-3.7


【解决方案1】:

%s,你想在那个位置插入一个变量吗?如果是这样 你需要做"some %s variable" % variable_to_inser。或者清洁工 方式,做f"some {productname} here"(f在开始时很重要 的字符串)。 – @Torxed

这解决了我的问题如下:

wmic_output = os.popen(f'''wmic product where "name like {variablename}" get name''').read()

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2021-01-01
    • 2022-12-21
    • 2016-09-21
    • 2020-04-16
    • 2010-10-28
    相关资源
    最近更新 更多