Python快速triage.py

2024-09-27 23:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试转换快速triage.py到Python3.4。我一直有个错误:

"File "RapidTriage.py" line 152. in (module) outputfile.write(p.stdout.read()) Type Error: must be str, not bytes"

这是密码

for cmd in cmds:
  split_cmd=cmd.split("::")
  outputfile.write("\t"+split_cmd[0]+":\t")
  p = subprocess.Popen(split_cmd[1], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
  outputfile.write(p.stdout.read())
outputfile.write("\n")

Tags: inpycmdread错误stdoutlinefile
2条回答

默认情况下,如果Popen调用上的universal_newlines=False,则Popen.stdout将以字节为单位读取,这是默认值。因此,如果Popen调用上的universal_newlines关键字参数未设置为True,则所有对p.stdout.read()的调用都将返回字节。因为默认值是False,所以读取的字节不是字符串,但是如果将其设置为True,那么p.stdout.read()应该返回str类型而不是字节。你知道吗

所以这会解决你的问题

p = subprocess.Popen(split_cmd[1], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
outputfile.write(p.stdout.read())

当数据在程序内存中时,这会将换行符转换为\n,但是write方法会在输出时将它们转换回特定于平台的形式。你知道吗

或者,您也可以通过将outputfile作为二进制文件打开来将数据作为二进制文件写入。你知道吗

outputfile = open(file, 'wb')

然后您可以按如下方式编写代码。你知道吗

for cmd in cmds:
  split_cmd=cmd.split("::")
  outputfile.write(('\t{0}:\t'.format(split_cmd[0])).encode(<optional encoding>))
  p = subprocess.Popen(split_cmd[1], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
  outputfile.write(p.stdout.read())
outputfile.write("\n".encode(<optional encoding>))

p.stdout.read()是bytes类型。您可能将outputfile打开为open(<filename>,"w")。把它改为写字节应该可以解决这个问题

ooutputfile = open(<filename>,"wb")

也可以在将数据写入文件时将字节转换为字符串

相关问题 更多 >

    热门问题