有时我需要计算某些东西的答案。由于我通常会打开终端屏幕,这是我询问此类数学问题的自然场所。
Python交互式shell非常适合这个目的,前提是你想要进入另一个shell,只是稍后又必须退出它。
但有时最好能够立即从命令行获得答案。Python具有-c命令选项,我发现它在处理单个命令并返回结果方面非常有用。我编写了以下bash shell脚本来利用它:
#!/bin/bash
# MHO 12-28-2014
#
# takes a equation from the command line, sends it to python and prints it
ARGS=0
#
if [ $# -eq 1 ]; then
ARGS=1
fi
#
if [ $ARGS -eq 0 ]; then
echo "pc - Python Command line calculator"
echo "ERROR: pc syntax is"
echo "pc EQUATION"
echo "Examples"
echo "pc 12.23+25.36 pc \"2+4+3*(55)\""
echo "Note: if calculating one single equation is not enough,"
echo "go elsewhere and do other things there."
echo "Enclose the equation in double quotes if doing anything fancy."
echo "m=math module ex. \"m.cos(55)\""
exit 1
fi
#
if [ $ARGS -eq 1 ]; then
eqn="$1"
python -c "import math; m=math; b=$eqn; print str(b)"
fi
#
示例输出
$ pc 1/3.0
0.333333333333
$ pc 56*(44)
2464
$ pc 56*(44)*3*(6*(4))
177408
$ pc "m.pi*(2**2)"
12.5663706144
请注意python -c
选项,有没有一种简洁的方式可以隐式地引用math模块,以便最后的pc命令可以格式化为pc"pi*(2 ** 2)"
?
python -c "from math import *; print $eqn"
。顺便说一句,与其在你的 bash 脚本中使用无数个echo
命令,不如使用 heredoc。还要注意一下任意精度计算器 bc,虽然语法不如 Python 那么好看,但它几乎在所有 Linux 系统上都通用。 - PM 2Ringbc
会更简单吧?例如像这样:bc -l <<< "4*a(1) * (2^2)"
。 - user000001