如何在交互式环境中使用脚本

2024-09-30 10:35:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下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

这个项目是我的.py当我这么做的时候

chmod +x my.py
python my.py

在这一步之后,我又回到了bashshell 我打开一个Python壳

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中


Tags: storekeypyself程序ifvaluedef
3条回答

把你的档案我的.py在Python中 那么

from my import ArithmeticSequence
s=ArithmeticSequence(1,2)

要运行的命令是:

python -i my.py

这将解析我的.py并定义名称ArithmeticSequence,然后将您放入Python shell中,您可以在其中以交互方式使用对象:

>>> s=ArithmeticSequence(1,2)
>>> 

你要么用

if __name__ == 'main':
    # Your code goes here. This will run when called from command line.

或者,如果您在python解释器中,则必须使用以下命令导入“my”:

>>> import my

相关问题 更多 >

    热门问题