#!/usr/bin/python3 # -*- coding: utf-8 -*- # %% standard in, out, err """ Every user of a UNIX or Linux operating system should know standard streams, i.e. input, standard output and standard error. They are commonly abbreviated as stdin, stdout, stderr. The standard input (stdin) is normally connected to the keyboard, while the standard error and output go to the terminal you are working in. These data streams can be accessed from Python via the objects of the sys module with the same names, i.e. sys.stdin, sys.stdout and sys.stderr. """ import sys for i in (sys.stdin, sys.stdout, sys.stderr): print(i) print("Going via stdout") sys.stdout.write("Another way to do it!\n") x = input("read value via stdin: ") print(x) print("type in value: ", sys.stdin.readline()) sys.stderr.write("Warning, log file not found starting a new one\n") # Overwrite sys.stdin and sys.stdout! # Tricky (notice what's happening) # The file is being printed to! print("Coming through stdout") # stdout is saved orig_stdout = sys.stdout with open("test.txt", "w") as fh: sys.stdout = fh print("This line goes to test.txt") # return to normal: sys.stdout = orig_stdout # Now, show debugger printed output did not contain above text # Doing it too early will crash debugger! # This is helpful for unit testing # Pay close attention here! # Show test.txt exists, and has content. orig_stdin = sys.stdin with open("test.txt", "r") as sys.stdin: line = input("This data is coming from test.txt") print(line) sys.stdin = orig_stdin """ If you want to have std-in and std-out with subprocess.run, like what would be this in bash: $ ./pythonscript.py whateverout then do this: """ import subprocess returnobject = subprocess.run(["ls", "-l"], capture_output=True) print(returnobject.stdout.decode()) with open("test.txt", "rb", 0) as input_file: with open("output.txt", "wb", 0) as output_file: subprocess.run( ["cat", "test.txt"], timeout=4, stdout=output_file, stderr=subprocess.PIPE, stdin=input_file, )