从Shell在Windows上运行Python

时间:2015-04-01 10:28:23

标签: python windows shell

所以我有一些名为'some_class.py'的脚本与python.exe位于同一个文件夹中:

from __future__ import print_function

class some_class:
    def say_it(self):
    print('hello')

def main():
    instance = some_class()
    instance.say_it()

if __name__ == '__main__':
    main()

当我在PowerShell中的Python Shell中尝试使用以下命令运行它时:

some_class.py

我明白了:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_class' is not defined

Python的版本是3.4.1。我做错了什么?

2 个答案:

答案 0 :(得分:2)

你通常不把你的python程序放到你安装python的文件夹中 - 这不是它应该如何。

此外,python在查找python模块时不会查看python.exe目录,它会查看$ PYTHONPATH(默认情况下,进入其库文件夹)并进入当前工作目录(这是您所在的目录) 你调用python.exe时,而不是其中 python.exe本身所在。

如果你想使用它,你还必须导入你的文件,所以在交互式shell中,你可能会这样做

import my_python_file

我认为你应该回到python.org并从头到尾阅读教程。它有一个关于处理文件,实际是什么模块以及如何使用其他文件的功能的很好的部分。

答案 1 :(得分:2)

如果你想使用文件名运行它,那么就不要从cmd提示符启动一个python shell python34 some_class.pyif __name__ == '__main__':表示执行脚本时将运行main()函数。如果您导入脚本将无法运行,那就是使用if __name__ == '__main__'