Python: use input from another command

I am wondering how I can control input from another command from a python script.

Example:

$ cat myfile.txt | my_python_script.py

How does my script control input from the cat command? How can I get input from these channel-supported commands?

... Many thanks.

+4
source share
2 answers

An easy and fairly universal way to do this is to use the fileinput module.

 import fileinput for line in fileinput.input() # do things with line 

This way you can use the script in the pipeline (as you need right now) or provide one or more files in the script as a parameter (think my_python_script.py input.txt input2.txt ).

+4
source

A good alternative to reading standard input through sys.stdin.readlines() : use the pipes module.

The pipe module defines a class for abstracting the concept of a pipeline — a sequence of converters from one file to another. Since the module uses the / bin / sh command lines, POSIX or a compatible shell for os.system () and os.popen () is required.

Here is a good tutorial .

+1
source

Source: https://habr.com/ru/post/1401452/


All Articles