代码以交互方式显示结果,而不是从shell运行时 [英] Code shows results when run interactively, but not when run from a shell

查看:107
本文介绍了代码以交互方式显示结果,而不是从shell运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一张海报借用这个小科学记数法脚本: Python - 如何将十进制转换为科学记数法

I borrowed this little scientific notation script from another poster: Python - How to convert decimal to scientific notation.

def format_e(n):
    a = '%E' % n
    return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]

format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'

format_e(Decimal('40000000000.00000000000000'))
# '4E+10'

format_e(Decimal('40812300000.00000000000000'))

该函数在从终端或Python Shell处理为模块时工作正常。但是,当运行像'python Converter.py'时,它会立即终止而不返回上面的三个示例。

The function works fine when manipulated as module from the Terminal or the Python Shell. However, when ran like 'python Converter.py' it terminates immediately without returning any of the three examples above.

推荐答案

解释器自动回显不返回 None 的任何表达式的结果。在脚本中,您需要显式地打印您要查看的结果:

The interactive interpreter auto-echoes the results of any expression that doesn't return None. In a script you need to explicitly print the results you want to see:

print format_e(Decimal('40800000000.00000000000000'))
print format_e(Decimal('40000000000.00000000000000'))
print format_e(Decimal('40812300000.00000000000000'))

这篇关于代码以交互方式显示结果,而不是从shell运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆