postgresql psql - 将查询和查询的输出写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20432998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
psql - write a query and the query's output to a file
提问by Wayne Conrad
In postgresql 9.3.1, when interactively developing a query using the psqlcommand, the end result is sometimes to write the query results to a file:
在 postgresql 9.3.1 中,当使用psql命令交互式开发查询时,最终结果有时是将查询结果写入文件:
boron.production=> \o /tmp/output
boron.production=> select 1;
boron.production=> \o
boron.production=> \q
$ cat /tmp/output
?column?
----------
1
(1 row)
This works fine. But how can I get the query itselfto be written to the file along with the query results?
这工作正常。但是如何将查询本身与查询结果一起写入文件?
I've tried giving psql the --echo-queries
switch:
我试过给 psql--echo-queries
开关:
-e, --echo-queries
Copy all SQL commands sent to the server to standard output as well.
This is equivalent to setting the variable ECHO to queries.
But this always echoes to stdout, not to the file I gave with the \o command.
但这总是与标准输出相呼应,而不是与我用 \o 命令给出的文件相呼应。
I've tried the --echo-all
switch as well, but it does not appear to echo interactive input.
我也试过这个--echo-all
开关,但它似乎没有回应交互式输入。
Using command editing, I can repeat the query with \qecho
in front of it. That works, but is tedious.
使用命令编辑,我可以\qecho
在它前面重复查询。这有效,但很乏味。
Is there any way to direct an interactive psql session to write both the query and the query output to a file?
有什么方法可以引导交互式 psql 会话将查询和查询输出写入文件?
回答by Luca Abbati
You can try redirecting the stdout to a file directly from your shell (Win or Linux should work)
您可以尝试将标准输出直接从您的 shell 重定向到一个文件(Win 或 Linux 应该可以工作)
psql -U postgres -c "select 1 as result" -e nomedb >> hello.txt
This has the drawback of not letting you see the output interactively. If that's a problem, you can either tail the output file in a separate terminal, or, if in *nix, use the tee
utility:
这样做的缺点是不能让您以交互方式查看输出。如果这是一个问题,您可以在单独的终端中拖尾输出文件,或者,如果在 *nix 中,请使用该tee
实用程序:
psql -U postgres -c "select 1 as result" -e nomedb | tee hello.txt
Hope this helps!
希望这可以帮助!
Luca
卢卡
回答by Blockhead
I know this is an old question, but at least in 9.3 and current versions this is possible using Query Buffer meta-commands shown in the documentation or \? from the psql console: https://www.postgresql.org/docs/9.3/static/app-psql.html
我知道这是一个老问题,但至少在 9.3 和当前版本中,使用文档中显示的查询缓冲区元命令或 \? 从 psql 控制台:https: //www.postgresql.org/docs/9.3/static/app-psql.html
\w or \write filename
\w or \write |command
Outputs the current query buffer to the file filename or pipes it to the shell command command.