python - 如何重定向从 python 脚本运行的 shell 脚本输出

标签 python shell

<分区>

我正在从 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 脚本输出重定向到我不想要的文件。

最佳答案

查看 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

关于python - 如何重定向从 python 脚本运行的 shell 脚本输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052676/

相关文章:

python - 在 Django 中使用 prefetch_related 连接 ManyToMany 字段

python - any() 的性能

shell - 如何在 awk 的 BEGIN block 中使用变量?

shell - 一行中的多个字符串的 grep

bash - 编写类似于 scp 的 bash 补全脚本

linux - bash 脚本 : how to get item name on a radiolist using dialog

python - 如何定位 Bokeh 小部件?

python - 如何更改字典的键?

python - python opencv-使用视频输入到图像路径界面api的最佳方法是什么

shell - 非交互模式下的stty