【问题标题】:How to redirect shell script output ran from a python script [duplicate]如何重定向从python脚本运行的shell脚本输出[重复]
【发布时间】:2016-10-29 09:24:15
【问题描述】:

我正在从 python 脚本执行几个 shell 脚本。一个特定的 shell 脚本(代码的最后一行)调用用于运行 Hive 查询以获取一些表信息,我想将此输出重定向到一个文件。这是我的 python 脚本的样子。

$ cat test.py
    import argparse
    from subprocess import call

    parser = argparse.ArgumentParser()
    parser.add_argument('-c','--cutoff',required=True)
    args = parser.parse_args()

    Table="elements_status_values_"+ args.cutoff
    call(["clear"])
    print ">> Running the hive query"
    call(["hive", "-S", "-e" "select * from %s order by rand() limit 2;" % cutoffTable])

当我执行此操作时,我会在终端上得到结果,但我需要将输出从 python 脚本重定向到一个文件,以使用输出进行更多操作。所以我基本上希望我的 Hive 查询输出被重定向到一个文件,以便我可以将该文件用于同一脚本中的其他操作。在 shell 脚本中,我们可以使用 '>' 将输出重定向到一个文件,但是有没有一种方法可以使用 python 来完成呢? 我搜索了与此相关的帖子,但所有帖子都将 python 脚本输出重定向到我不想要的文件。

【问题讨论】:

标签: python shell


【解决方案1】:

查看documentation 以获得subprocess.call:您可以提供stdoutstdin 等参数。

with open('output.txt', 'w') as output_file:
    call([your_stuff], stdout=output_file)

这是一种通用方式 - 类似的方法也适用于 C 和许多其他语言。

旧的特定于 python 的方法是使用 subprocess.check_output 而不是 subprocess.call

当前特定于 python 的方法是使用 subprocess.run 并逐字检查其标准输出:output = run(..., check=True, stdout=PIPE).stdout

【讨论】:

  • 更正:需要包含'w'写入模式如下:with open('output.txt','w') as ...
猜你喜欢
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2014-09-01
  • 2017-02-11
  • 2018-08-12
相关资源
最近更新 更多