Mic*_*ens 10 python bash calculator command-line-interface
我时不时地得到计算的答案.因为我通常有一个终端屏幕打开,这是我提出这样的数学问题的自然场所.
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
#
Run Code Online (Sandbox Code Playgroud)
$ pc 1/3.0
0.333333333333
$ pc 56*(44)
2464
$ pc 56*(44)*3*(6*(4))
177408
$ pc "m.pi*(2**2)"
12.5663706144
Run Code Online (Sandbox Code Playgroud)
问题,记住python -c选项,是否有任何简洁的方法来隐式引用数学模块,以便最后一个pc命令可能被格式化为pc "pi*(2**2)"?
Ara*_*Fey 16
您可以使用
from math import *
Run Code Online (Sandbox Code Playgroud)
将所有常量和函数从数学模块导入到全局范围.