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: ")
解决方案
当您使用该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')
推荐阅读
- vba - Excel:公式执行的动态数据交换 API 问题
- javascript - 有没有办法让 VSCode 从它们的注释行中显示关于 JavaScript 函数的附加智能信息?
- php - 删除令牌 EasyAdmin 3
- python - Python:保持pandas.multiindex的最后n列相对于列索引级别1
- haskell - 为什么必须手动验证 Haskell 的类型类法则?
- c - 与 Windows 中的管道一起使用时,STDIN、STDOUT 无法流式传输正确的输出
- c++ - MacOS:如何启动 gui QProcess 并将其置于最前面?
- html - 基于类的详细视图不返回模板
- c# - 如何通过仅使用 1 个坐标跟随我的玩家位置来移动敌人
- javascript - 如何像在 Excel 中一样在 JavaScript(仅 JS)中使用数字、字母数字、字母对数组进行排序?