【问题标题】:Python subprocess.Popen() does not transfer ® symbol and instead translates the literal letter 'r' as argument to batch filePython subprocess.Popen() 不传输 ® 符号,而是将文字字母 'r' 作为参数转换为批处理文件
【发布时间】:2021-09-28 02:11:27
【问题描述】:

我正在编写一个 Python 脚本来运行一个批处理文件,并为其提供几个参数以在整个批处理脚本中输入。不幸的是,当我遇到特殊字符 ® 时,批处理脚本将其识别为文字字母“r”。我的代码目前看起来像这样(以及我尝试过但后来注释掉的一堆代码。我还留下了我的 cmets,以便您了解我尝试过的内容以及我的心态在哪里):

    item = subprocess.Popen('"file.bat", {}, {}, {}, {}'.format(arg1, arg2, arg3, arg4), universal_newlines=True, encoding='utf-8', stdin=subprocess.PIPE, stdout=subprocess.PIPE) #stdin=subprocess.PIPE #shell=True # Manually added ^® to input which also failed. CMD recognizes ® but displays 'r' when typing. 
    # item = item.communicate(str.encode("utf-8"))
    # data = item.communicate()
    # print(data[0])
    for line in item.stdout:
        print(line) # .decode('utf-8')

    # Since windows displays 'r' but still recognizes the character as ®, the process is interpretting the literal text on the prompt. Need to interpret the value. Tried encoding parameters to no avail. 
    # Try stdin=subprocess.PIPE with encode('utf-8)
    # Try removing r in beginning of .Popen

我的参数用双引号括起来。

我尝试了几种编码“utf-8”的变体

我尝试使用 r'"file.bat", {}, {}, {}, {}' 将 Popen 读取为字符串文字

我注意到,当我将 ® 粘贴到 Visual Studio Code 终端时,它最初会显示为“r”,但是如果我回显它,结果显示将是 ®。

我尝试使用转义字符 ^®

【问题讨论】:

    标签: python shell batch-file encoding subprocess


    【解决方案1】:

    我以迂回的方式解决了这个问题。看起来通过将参数传递给 python.exe 可以完全避免。

    我将 ASCII 表的 extended version (批处理文件不支持的字符)复制粘贴到一个文本文件中,然后将其保存为 excel 作为一个制表符分隔的文件,编码为“utf-8”。从那里我使用 Pandas 将其作为数据框阅读。

        df = pd.read_csv('extended_ascii.csv')
        for index, row in df.iterrows():
            char = row['Symbol']
            BIN = row['BIN']
            arg1 = arg1.replace(char, "BIN" + str(BIN))
            arg2 = arg2.replace(char, "BIN" + str(BIN))
            arg3 = arg3.replace(char, "BIN" + str(BIN))
            arg4 = arg4.replace(char, "BIN" + str(BIN))
    

    -运行批处理文件-

    返回python脚本:

        for line in Lines:
            for index, row in df.iterrows():
                char = row['Symbol']
                BIN = row['BIN']
                line = line.replace("BIN" + str(BIN), char)
    

    我的任何参数文本都不太可能包含 BIN########,这似乎是使用此方法的唯一弱点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多