簡體   English   中英

重定向標准輸入和標准輸出

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM