0

So I've found a way to read from stdin in python, which is as follows:

if not sys.stdin.isatty():
    stdin = sys.stdin.read()

but for a statement like this,

echo Hello | program.py

I only get stdin = Hello, which is how it should work. My question is, is there a way to get the whole command as a string in the python program, for example, getting "echo Hello" in the previous exmaple?

Any alternative to get the command in program.py will work too. Thanks :)

Haven't got a good idea yet, so have not tried anything as of yet.

  • 1
    Can't you just do `echo "echo 'Hello'" | program.py`? – MrLatinNerd Jul 21 '23 at 09:12
  • That was just an example, I want both the command and its output, echo Hello and hello in seperate strings – Nauto the Boss Jul 21 '23 at 09:16
  • You can call external programs within Python: https://stackoverflow.com/a/89243/1867662. So one way you could achieve what you want is to input the entire command, and then run it using subprocess.run. – MrLatinNerd Jul 21 '23 at 09:30
  • Note, that `echo Hello` likely _finishes_ before program.py has a chance to run, because pipe buffering. The information that `echo Hello` has existed may just no longer be there at all at the time program.py runs. – KamilCuk Jul 21 '23 at 09:50

1 Answers1

1

No, you can not. You could think of launching a program as creating a box with 2 tubes, stdin and stdout (and stderr but nvm).

With echo Hello | program.py your creating 2 boxes, one for echo and one for python, then with | you pipe echo's stdout to python's stdin.

You could launch python first, then execute echo Hello, however you would need to modify your python script first to wait for inputs on stdin, then to pass the inputs to a shell subprocess's stdin, read that subprocess stdout and return that to you through it's own stdout.

Daviid
  • 630
  • 4
  • 17