[英]Redirecting stdin and stdout
当我运行命令时
python3./db.py 'blah blah blah' > output.html
output.html中出现“Enter your name: Enter your password:”字样。 我不希望这个存在。 它正在接受用户名和密码,但不会提示命令行“输入您的姓名”。 知道我该如何解决这个问题吗?
这是我正在运行的代码:
import psycopg2
import sys
name = input("Enter your name: ")
passwd = input("Enter your password: ")
当您使用input(prompt)
function 时, prompt
的内容将发送到标准 output。这在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')
只需使用 stderr 而不是 stdout:
print("Enter your password: ", file=sys.stderr, flush=True)
password = input()
通过这种方式,您可以将提示和干净的 output 重定向到一个文件。
您可以尝试将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 中进行写作。尝试将所需的 output 文件名作为参数/参数传递给脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.