【问题标题】:Running Python on Windows from Shell从 Shell 在 Windows 上运行 Python
【发布时间】:2015-04-01 10:28:22
【问题描述】:

所以我有一些名为“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。我做错了什么?

【问题讨论】:

  • 试试“python some_class.py”。

标签: python windows shell


【解决方案1】:

如果你想使用文件名运行它,那么不要从 cmd 提示符启动 python shell 只是python34 some_class.pyif __name__ == '__main__': 意味着main() 函数将在脚本执行时运行。如果你导入脚本它不会运行,那就是使用if __name__ == '__main__'的重点

【讨论】:

    【解决方案2】:

    您通常不会将您的 python 程序放入您安装 python 的文件夹中——这不是应该的。

    另外,python 在查找 python 模块时不会查找 python.exe 的目录,它会查找 $PYTHONPATH(默认情况下,查找其库文件夹)和当前工作目录(即您所在的目录) 你调用了python.exe,而不是在哪里 python.exe本身在哪里。

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

    import my_python_file
    

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

    【讨论】:

    • 我尝试从 some_class.py 所在的文件夹调用 python.exe。然后我导入了我的文件,但是在尝试实际使用该类时遇到了同样的错误。我也没有在 python.org 上找到任何涉及模块理论的教程。按照@padraic-cunningham 的建议从外壳外部启动文件确实有效。
    • Python 的导入系统使用sys.path,而不是PYTHONPATH。该可选环境变量只是扩展sys.path 的众多方式之一。
    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多