【问题标题】:Weird ouput using Popen in ST3在 ST3 中使用 Popen 的奇怪输出
【发布时间】:2015-12-06 22:02:40
【问题描述】:

我正在为 Sublime 文本开发一个插件,由于该环境中 python 的一些限制,我正在尝试使用 Popen 获得 json 答案,我正确接收数据,但似乎 Popen 在输出。

这是输出

(b'{"trink": {"id": "12"}}\r\n')

但应该是

{"trink": {"id": "12"}}

这就是我打电话的方式:

process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell=True)
output = process.communicate()
print(output)

output = process.communicate()[0]

仅从原始输出中消失 ()

如何获得干净的输出?

我正在使用 Sublime text 3 Build 3083 Windows 10-64b

【问题讨论】:

    标签: python plugins sublimetext3 popen


    【解决方案1】:

    ST论坛的一位用户回答我:

    对于初学者来说,这 100% 是 Python 问题,与 崇高的文字。这也不是限制,而是功能。从字面上看。

    首先,communicate 返回一个带有 (stdout_data, stderr_data) 的元组。 您很可能只需要标准输出部分,因此您对该元组进行切片 与[0]

    其次,通信返回的数据默认是一组 字节。如果你愿意,就查一下。字节用b 表示 文字字符串的前面,可以使用 .decode() 方法,带有字符集的参数。这 可能是 utf-8 或 cp1252 或只是 locale.getpreferredencoding()。如果您将 Popen 与 universal_newlines=True 参数,Python 会进行这种转换 自动为您服务。

    最后,你到现在为止的字符串在 最后,因为这就是您使用的任何工具的方式 输出。如果有问题,您必须使用 .strip() 将其剥离(因为 它是 json,很可能不是)。

    那么我们现在得到了什么?

    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
    output = process.communicate()[0]#.strip()
    print(output)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多