【问题标题】:subprocess python reading output [duplicate]子进程python读取输出[重复]
【发布时间】:2018-09-04 18:51:58
【问题描述】:

我正在尝试使用 python 中的子进程运行命令并尝试读取它的输出并将其复制到文件中。 我的代码是:

    command = "%s -sK:\\run_one_test.csh %s %s" % (PATH, file, VERSION)
    p = subprocess.Popen(command,stdout=subprocess.PIPE)

    text = p.communicate()[0]
    return_code = p.returncode




    with open("%s/%s%s" % (LOG_DIR, file, LOG_EXT), "w") as f:


        f.writelines([l.decode for l in text.split('\n')])

        f.close()

但是当我使用分割线时,我收到错误消息:

    f.writelines([l.decode for l in text.split('\n')])
TypeError: a bytes-like object is required, not 'str'

为什么会这样?我用解码。 另外,这是使用“\n”分割代码行的正确方法吗? 谢谢。

【问题讨论】:

标签: python


【解决方案1】:

textsubprocess.Popen 的结果,在python 3 中,这是一个bytes 对象。您不能使用字符串对其进行拆分(text.split(b"\n") 可以,但您的代码中存在更多问题,所以算了吧)。

那么,您没有调用 decode(缺少括号)。在text 上调用decode 可以:text.decode()

现在使用split('\n'),您将删除行尾,这样就无法正常工作(单行文件,哎呀)。你需要:

f.writelines(text.decode().splitlines(True))

True 参数告诉函数保留行尾字符)

但毕竟为什么要拆分再次写入行?,只需将文件转储为bytes,无需后处理:

with open("%s/%s%s" % (LOG_DIR, file, LOG_EXT), "wb") as f:
    f.write(text)

但是为什么要存储输出以将其写回文件呢?只需将文件句柄传递给subprocess.call

with open("%s/%s%s" % (LOG_DIR, file, LOG_EXT), "wb") as f:
   retcode = subprocess.call(command,stdout=f)

如果命令返回码不为 0,则强制异常:

   subprocess.check_call(command,stdout=f)

因此,根据您是要对行进行后处理、对缓冲区进行后处理还是根本不进行后处理,您可以选择上述 3 种(可能已修改)解决方案之一。

旁注:不要将命令编写为字符串,只需传递参数即可:

command = "%s -sK:\\run_one_test.csh %s %s" % (PATH, file, VERSION)

变成:

command = [PATH,"-sK:\\run_one_test.csh",file,VERSION]

(作为奖励,如果需要,报价会自动处理)

【讨论】:

  • 您应该更喜欢subprocess.check_call() 或者更好的是subprocess.run()。另见stackoverflow.com/questions/4256107/…
  • run 需要 python 3.5。我切换到call,因为它更适合Popen。我们不知道该命令的返回码是什么
猜你喜欢
  • 2019-02-21
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 2012-04-06
  • 2014-02-10
  • 2015-01-20
  • 1970-01-01
  • 2019-04-26
相关资源
最近更新 更多