Вопрос

I can run bc with Python with the following code:

subprocess.Popen("bc", stdout=subprocess.PIPE).communicate()[0]

However, this only launches bc, and I have to manually input whatever I want, for example, 1+1. I want to use Python to send 1+1 to bc and get the output. How would I do that?

Это было полезно?

Решение

Figured it out. You have to have stdin as well as stdout, and call communicate with a string that ends in a newline, like this:

p = subprocess.Popen("bc", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate('1+1\n')

Where out is the output you want.

Другие советы

How about doing something like this:

dogface@computer ~
$ cat oneplusone
1+1
quit

dogface@computer ~
$ python3
Python 3.2.3 (default, Jul 23 2012, 16:48:24)
[GCC 4.5.3] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(["bc", "-q", "oneplusone"])
2
0
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top