如何在交互式shell中使用脚本

我写了下面的python程序


#! /usr/bin/python

def checkIndex(key):

    if not isinstance(key, (int, long)): raise TypeError

    if key<0: raise IndexError


class ArithmeticSequence:

    def __init__(self, start=0, step=1):

        self.start = start      # Store the start value

        self.step = step        # Store the step value

        self.changed = {}       # No items have been modified

    def __getitem__(self, key):

        checkIndex(key)

        try: return self.changed[key]

        except KeyError:

            return self.start + key*self.step

    def __setitem__(self, key, value):

        checkIndex(key)

        self.changed[key] = value

我做的时候程序是my.py


chmod +x my.py

python my.py

在执行完此步骤后,我将回到bash shell


user@ubuntu:~/python/$ python

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 

[GCC 4.6.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.


>>> s=ArithmeticSequence(1,2)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'ArithmeticSequence' is not defined

我如何给程序输入并运行它,因为它已保存在vi中


慕妹3242003
浏览 114回答 3
3回答

拉丁的传说

好吧,您要么必须使用以下程序作为程序来运行它if __name__ == 'main':&nbsp; &nbsp; # Your code goes here. This will run when called from command line.或者,如果您在python解释器中,则必须使用以下命令导入“ my”:>>> import my
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python