简体   繁体   中英

Redirecting stdin and stdout

When I run the command

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

The text "Enter your name: Enter your password:" appears in output.html. I do not want this to be there. It's accepting username and password but it isn't prompting the command line with "Enter your name". Any idea how I fix this?

This is the code I'm running:

import psycopg2
import sys

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

When you use the input(prompt) function, the contents of prompt will be sent to standard output. That's in the documentation for 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

If you wish the result to be written to a file, you should do that in the code itself, rather than redirecting stdout to a file.

with open(filename, 'w') as file:
    file.write(name+'\n')
    file.write(passwd+'\n')

Just use stderr instead of stdout:

print("Enter your password: ", file=sys.stderr, flush=True)
password = input()

This way you'll have both prompt and clean output redirected to a file.

You could try redirecting your input calls to stderr . I recommend using contextlib so that all calls are redirected without having to specify file= every time. Here's a minimal example:

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}")

And when running:

$ 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

Per my comment, however, I would suggest doing the writing in your actual Python. Try passing the desired output filename as a parameter/argument to the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM