【问题标题】:python3.2 using subprocess.popen - need to format resulting stdout for writing to a filepython3.2 使用 subprocess.popen - 需要格式化生成的标准输出以写入文件
【发布时间】:2012-11-28 21:55:47
【问题描述】:

我正在使用subprocess 运行命令(来自衍生的守护程序)并尝试将结果写入文件。来自Popen 的结果字符串是bytestring。在写入文件之前,如何将其格式化为人类可读的内容?使用python3.2

试过了:

print (x,file=o)
f.write(str(rc.so))
print (str(rc.so) + "\n")

没有任何东西最终看起来可读..

可疑代码:

  rc = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE,   stderr=subprocess.PIPE)
  x = rc.stdout.readlines()
  rc.so, rc.se = rc.communicate()
  with open(of,'w') as o, open(ef,'w') as e:
     print (str(rc.so) + "\n",file=o)

【问题讨论】:

  • 你试过解码吗? your_string.decode('utf-8')?

标签: python python-3.2


【解决方案1】:

你需要解码它:

my_byte_string.decode('utf-8')

utf-8 可能不是适合您情况的最佳解码选择,它是众多可用选项之一。

所以打印语句应该更像:

print (rc.so.decode('utf-8') + "\n",file=o)

【讨论】:

  • 你可能需要sys.getdefaultencoding()而不是utf-8。当然,假设另一个程序表现良好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 2011-11-30
  • 2016-11-30
  • 2018-12-07
  • 2011-04-09
  • 1970-01-01
  • 2020-11-25
相关资源
最近更新 更多