重定向标准输入和标准输出

时间:2020-11-12 03:30:48

标签: python

当我运行命令时

python3 ./db.py 'blah blah blah' > output.html

output.html中显示文本“输入您的名称:输入您的密码:”。我不希望这个存在。它接受用户名和密码,但不使用“输入您的名称”提示命令行。知道我该如何解决吗?

这是我正在运行的代码:

import psycopg2
import sys

name = input("Enter your name: ")
passwd = input("Enter your password: ")

3 个答案:

答案 0 :(得分:0)

使用input(prompt)函数时,prompt的内容将发送到标准输出。在input()的文档中:

 input?
Signature: input(prompt=None, /)
Docstring:
Read a string from standard input.  The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
Type:      builtin_function_or_method

如果希望将结果写入文件,则应在代码本身中执行此操作,而不是将stdout重定向到文件。

with open(filename, 'w') as file:
    file.write(name+'\n')
    file.write(passwd+'\n')

答案 1 :(得分:0)

只需使用stderr代替stdout:

print("Enter your password: ", file=sys.stderr, flush=True)
password = input()

这样,您便可以将提示和清除输出都重定向到文件。

答案 2 :(得分:0)

您可以尝试将input呼叫重定向到stderr。我建议使用contextlib,以便所有呼叫都被重定向,而不必每次都指定file=。这是一个最小的示例:

import contextlib
import sys

name, passwd = None, None
with contextlib.redirect_stdout(sys.stderr):
    print("This does not appear in stdout.")

    name = input("Please enter your name: ")
    passwd = input("Please enter your password: ")

print("This still appears in stdout.")
print(f"name = {name}")
print(f"pass = {passwd}")

运行时:

$ python ./temp.py > temp-out.txt
This does not appear in stdout.
Please enter your name: Matt
Please enter your password: abc

$ cat ./temp-out.txt
This still appears in stdout.
name = Matt
pass = abc

但是,根据我的评论,我建议您使用实际的Python进行编写。尝试将所需的输出文件名作为参数/参数传递给脚本。