【问题标题】:Python calculator - Implicit math modulePython 计算器 - 隐式数学模块
【发布时间】: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)"

【问题讨论】:

  • 您可以将其简化为python -c "from math import *; print $eqn"。顺便说一句,您应该使用heredoc,而不是在您的 bash 脚本中使用无数个 echo 命令。另请查看任意精度计算器bc。语法不如 Python 好,但在 Linux 系统上几乎是通用的。
  • 不错的工具,你应该把它放在 GitHub 上 :)
  • 很好,但使用bc 不是更简单吗?比如bc -l <<< "4*a(1) * (2^2)"

标签: python bash calculator command-line-interface


【解决方案1】:

你可以使用

from math import *

将数学模块中的所有常量和函数导入全局范围。

【讨论】:

    【解决方案2】:
    if [ $ARGS -eq 1 ]; then
      eqn="$1"
      python -c "from math import *; b=$eqn; print str(b)"
    fi
    
    $ pc "pi*(2**2)"
    12.5663706144
    

    太棒了!谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2014-03-09
      • 2022-07-04
      • 2017-11-05
      • 2014-10-19
      相关资源
      最近更新 更多