【发布时间】:2015-02-25 14:42:55
【问题描述】:
我时不时需要得到计算的答案。因为我通常会打开一个终端屏幕,这是我提出此类数学问题的自然场所。
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 选项,是否有任何简洁的方法可以隐式引用数学模块,以便将最后一个 pc 命令格式化为pc "pi*(2**2)"?
【问题讨论】:
-
不错的工具,你应该把它放在 GitHub 上 :)
-
很好,但使用
bc不是更简单吗?比如bc -l <<< "4*a(1) * (2^2)"。
标签: python bash calculator command-line-interface