-2

So I'm making a program where it prints a random string of digits/letters and I want it to print onto the console as well into a text file.

  print ( ''.join(random.choice(f"{letters2}{letters}{digits}") for i in range(0, option2)) )
  # line above prints into console
  if question == 1:
    with open('passwords.txt', 'a') as f:
      sys.stdout = f 
      print( ## )
      sys.stdout = original_stdout 
  # I'm trying to get what it outputs to the console to print to the file aswell


Thanks

LiamC
  • 1

1 Answers1

0

On Unix systems, you can achieve this by piping the output of your script to the tee command, which displays it in the terminal and also writes it to whatever file name you provide:

$ python3 -c "print('hello world')" | tee out.txt
hello world
$ cat out.txt
hello world

Note that the first command doesn't need to be a Python script - this is a general solution for simultaneously viewing and saving the output of any program.

Andrew Eckart
  • 1,618
  • 9
  • 15