0

I'd like to translate the shell code below to python code.
subprocess.Popen is used for doing it?
I've tried it, but I don't understand how to give (1),(2) commands.

sh> cat a.sh
dc << EOF
  20 5 / p    --(1)
  10 4 * p    --(2)
EOF
sh> sh a.sh
4
40

dc is just an example program for asking a question.
This can be replaced with any program which acts like this.
python version is 2.7.6. (Maybe sh module is not included in this version so it seems I can't use sh.Command)

cloudrain21
  • 649
  • 5
  • 17
  • 1
    Possible duplicate of [Python - How do I pass a string into subprocess.Popen (using the stdin argument)?](http://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument) – Remi Guan Nov 15 '15 at 12:25
  • Using Python will straightaway give you arbitrary precision calculation, without using `dc`. Just test them out in any Python interactive session. – Vivek Rai Nov 15 '15 at 12:27
  • 1
    @VivekRai: Because OP said *dc is just an example program for asking a question.* So I think this use `dc` here *is just an example program*. So OP is asking about...see the dupe. – Remi Guan Nov 15 '15 at 12:41

1 Answers1

0

Thanks.

>>> from subprocess import Popen,PIPE,STDOUT
>>> p = Popen(['dc'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
>>> output = p.communicate(input=b'20 5 / p\n10 4 * p')[0]
>>> print(output.decode())
4
40
cloudrain21
  • 649
  • 5
  • 17