【问题标题】:How to run a python file (.py) from the windows command-line without having to type python first?如何从 Windows 命令行运行 python 文件 (.py) 而无需先键入 python?
【发布时间】:2015-09-20 00:27:48
【问题描述】:

假设我有一个名为 file.py 的 python 文件。 通常要从命令行运行此文件,我会这样做:

python path\to\file\file.py

我的问题是,是否可以在文件路径前没有 python 的情况下这样做:

path\to\file\file.py

或者,如果我的环境变量中有 file.py 的路径,只需:

file.py

我想值得注意的是,我想使用一个接受命令行参数的 python 文件来执行此操作。谢谢:)

【问题讨论】:

  • 如果你使用 Cygwin,你可以包含一个 hash bang ("#! /usr/bin/env python") 并使你的文件可执行("chmod a+x path/to/file.py ") 以便可以直接在 Cygwin 中调用。祝你好运,内置的 WIndows 命令行,虽然......那个解释器很糟糕。
  • 在 Unix 或 Linux 上,我们在脚本顶部有像 #!/usr/bin/env python 这样的 SheBang(或 HashBang)。我不知道 Windows 是否支持这个。
  • 在这里查看文档:docs.python.org/2/faq/…
  • Windows,正如它在标题中所说的那样。

标签: python windows python-2.7 command-line pycharm


【解决方案1】:

您面临的问题是您的 python 应用程序实际上并不是一个应用程序。它是一个解释脚本。这是因为 Python 是 Interpreted Language

这类似于您有一个 Word 或 Excel 文档。这些由它们的应用程序解释:分别是 Word 和 Excel。操作系统知道使用哪个应用程序使用注册的关联程序来解释它们。

官方 Python 常见问题解答在这里解释了这一点: https://docs.python.org/2/faq/windows.html#how-do-i-make-python-scripts-executable

【讨论】:

  • 我建议阅读整个页面以及官方Using Windows 页面以获取更多信息。
猜你喜欢
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
相关资源
最近更新 更多