如何从控制台上的脚本文件中调用注释部分

时间:2015-10-14 22:16:37

标签: python console

所以我编写了我的第一个python脚本(test.py),现在我想在控制台上为函数test1调用docstring,但没有运气

我的剧本:

import os
os.system('cls')
def test1 (a , b ):
    """
    Learning Python to make a better world
    This is my first program
    """
    c = a+b
    print (c)

test1(1,2)
print (test1.__doc__)

但是当我在控制台上导入脚本时,这就是我得到的

C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)]
import test
print(test1.__doc__)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'test1' is not defined
print(test.test1.__doc__)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'module' object has no attribute 'test1'

不确定我在这里做错了什么,一定是非常基本的。

2 个答案:

答案 0 :(得分:1)

你肯定会导入一些test模块,这些模块存在于由其他Python软件包安装的真实python中,而不是你的test.py。在这种简单的情况下,您需要从与python相同的目录运行test.py并验证test模块是否实际导入,如果相对导入它应该如下所示:

>>> import test
>>> print(test)
<module 'test' from 'test.pyc'>

否则会显示如下内容:

>>> import test
>>> print(test)
<module 'test' from '/usr/lib/python3.4/test/__init__.py'>

最佳做法是,不要使用test.py为临时模块命名,保留单元/功能测试。

答案 1 :(得分:1)

Python3有一个test模块,仅供内部使用。请参阅:https://docs.python.org/3.4/library/test.html

因此,如果您将脚本保存到名为test.py的文件中,则导入该脚本的唯一方法是在与test.py脚本相同的目录上运行python console。只需将文件名更改为mytest.py,然后执行import mytestprint(mytest.test1.__doc__)即可避免出现问题。