0

In bash, you can do echo a | python -c "print('example:', input())" and you will get an output of example: a. How can you do the same thing in python.

I have tried doing this:

pid = os.fork()
if not pid:
    os.dup2(0, 1)
    os.execv("/usr/local/bin/python3", ["/usr/local/bin/python3", "-c", "print('example:', input())"])
else:
    subprocess.call(["echo", "a"])

and I have tried this:

proc1 = subprocess.Popen(["echo", "a"], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(["python", "-c", "print('example:', input())"], stdin=subprocess.PIPE)
proc2.stdin.write(proc1.stdout.read())

but both times this error was raised:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError
  • The second example works for me if I change `"python"` to `"python3"` in `proc2`. That depends on whether Python 2 or Python 3 is set up to be used by default in your OS if the `python` command is invoked. – mkrieger1 Mar 20 '20 at 11:22
  • See also: https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python-3 – mkrieger1 Mar 20 '20 at 11:22
  • Thanks, that question answered my question. Although I added this line: `open(1, 'wb').write(output)` – a_random_programmer Mar 20 '20 at 11:28

0 Answers0