-1

这是一个 Python 模块,它为多项式求值器提供了便利。它实际上只不过是一个文件中的一堆 Python 代码(主要是函数定义)。模块的名称是文件的名称,加上 .py 后缀。文件的文本中没有给出模块名称,所以我可以通过简单地重命名文件来重命名模块。

使用模块后,Python 将创建一个具有相同名称和扩展名.pyc 的文件。这是模块的字节码。Python 根据需要创建或重新创建这些,所以我真的不需要对它们做任何事情。

问题是:Python 不会创建 .pyc 扩展名。为什么?

# This module contains operations to manipulate polynomials.
#

# Need some string services, and some standard system services.
import string, sys

#
# Function to evaluate a polynomial at x.  The polynomial is given
# as a list of coefficients, from the greatest to the least.  It returns
# the value of the polynomial at x.
def eval(x, poly):
'''Evaluate at x the polynomial with coefficients given in poly.
The value p(x) is returned.'''

sum = 0
while 1:
    sum = sum + poly[0]     # Add the next coef.
    poly = poly[1:]         # Done with that one.
    if not poly: break      # If no more, done entirely.
    sum = sum * x           # Mult by x (each coef gets x right num times)

return sum


def read(prompt = '', file = sys.stdin):
'''Read a line of integers and return the list of integers.'''

# Read a line
if prompt: print prompt,
line = file.readline()
if not line: 
    raise EOFError, 'File ended on attempt to read polynomial.'
line = line[:-1]
if line == 'quit':
    raise EOFError, 'Input quit on attempt to read polynomial.'

# Go through each item on the line, converting each one and adding it
# to retval.
retval = [ ];
for str in string.split(line):
    retval.append(int(str))

return retval

#
# Create a string of the polynomial in sort-of-readable form.
def srep(p):
'''Print the coefficient list as a polynomial.'''

# Get the exponent of first coefficient, plus 1.
exp = len(p)

# Go through the coefs and turn them into terms.
retval = ''
while p:
    # Adjust exponent.  Done here so continue will run it.
    exp = exp - 1

    # Strip first coefficient
    coef = p[0]
    p = p[1:]

    # If zero, leave it out.
    if coef == 0: continue

    # If adding, need a + or -.
    if retval:
        if coef >= 0:
            retval = retval + ' + '
        else:
            coef = -coef
            retval = retval + ' - '

    # Add the coefficient, if needed.
    if coef != 1 or exp == 0:
        retval = retval + str(coef)
        if exp != 0: retval = retval + '*'

    # Put the x, if we need it.
    if exp != 0:
        retval = retval + 'x'
        if exp != 1: retval = retval + '^' + str(exp)

# For zero, say that.
if not retval: retval = '0'

return retval
4

1 回答 1

2

这里

当通过在命令行上给出其名称来运行脚本时,脚本的字节码永远不会写入“.pyc”或“.pyo”文件。因此,可以通过将脚本的大部分代码移至模块并使用导入该模块的小型引导脚本来减少脚本的启动时间。

因此,如果要创建.pyc文件,则必须导入脚本,而不仅仅是从命令行运行它。例如,你可以做

python -c "import myscript"

而不是做

python myscript.py
于 2013-02-06T16:35:18.467 回答