Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 重定向标准输入和标准输出_Python - Fatal编程技术网

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

Python 重定向标准输入和标准输出,python,Python,当我运行命令时 python3./db.py'blah blah'>output.html 文本“输入您的姓名:输入您的密码:”显示在output.html中。我不希望这件事发生。它接受用户名和密码,但不会提示命令行“输入您的姓名”。知道我该怎么解决吗 这是我正在运行的代码: import psycopg2 import sys name = input("Enter your name: ") passwd = input("Enter your passwor

当我运行命令时

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

文本“输入您的姓名:输入您的密码:”显示在output.html中。我不希望这件事发生。它接受用户名和密码,但不会提示命令行“输入您的姓名”。知道我该怎么解决吗

这是我正在运行的代码:

import psycopg2
import sys

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

使用
输入(提示)
功能时,
提示的内容将发送到标准输出。这在
input()
的文档中:

如果希望将结果写入文件,则应在代码本身中执行此操作,而不是将
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()

通过这种方式,您可以将提示和清除输出重定向到文件。

您可以尝试将
输入调用重定向到
stderr
。我建议使用
contextlib
,这样所有调用都可以重定向,而不必每次都指定
file=
。下面是一个简单的例子:

with open(filename, 'w') as file:
    file.write(name+'\n')
    file.write(passwd+'\n')
导入上下文库
导入系统
名称,passwd=None,None
使用contextlib.redirect_stdout(sys.stderr):
打印(“这不会出现在标准输出中。”)
name=输入(“请输入您的姓名:”)
passwd=input(“请输入您的密码:”)
打印(“这仍然显示在标准输出中。”)
打印(f“name={name}”)
打印(f“pass={passwd}”)
运行时:

$python./temp.py>temp-out.txt
这不会出现在标准输出中。
请输入您的姓名:Matt
请输入您的密码:abc
$cat./temp-out.txt
这仍然出现在stdout中。
name=Matt
通过=abc

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

使用重定向执行此操作的原因是什么?您是否可以将输出文件名作为参数传递,并在Python中进行编写?我认为这将有助于找到一个更“合适”的解决方案。要么将提示文本显式写入stderr,要么将html输出文本显式写入文件。