首页 > 解决方案 > 重定向标准输入和标准输出

问题描述

当我运行命令时

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

文本“输入您的姓名:输入您的密码:”出现在 output.html 中。我不希望它在那里。它接受用户名和密码,但没有用“输入您的姓名”提示命令行。知道我如何解决这个问题吗?

这是我正在运行的代码:

import psycopg2
import sys

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

标签: python

解决方案


当您使用该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')

推荐阅读