python 如何从命令行知道 运行?

How does python know to run from the command line?

嗨,我注意到每当从命令行(使用 windows 8.1)我输入

python file.py

它自动知道我想写 python.exe file.py

它是如何做到这一点的?

我安装了 Anaconda,我知道我有一个指向 python.exe 的环境变量。但这并不能解释为什么我不需要每次都输入 python.exe。

Python 使用路径搜索。在环境变量列表中找到 PATH。

如果您不写 python 而只是双击该文件,则会搜索注册表。

您可以从命令行使用 ftype 和 assoc 查看内容并将文件与程序相关联。参见例如http://www.fileformat.info/tip/microsoft/assocftype.htm

如果省略扩展名,也会搜索注册表。此命令 shell 搜索环境变量 PATHEXT 和注册表以查找 python.exe。此后,它正在使用注册表查找位置。

当您从 Spyder 中注册您的 python 发行版时,会进行这些更改。

您可以像我在开头写的那样使用 ftype 和 assoc 来显示此信息。


这不是 python 功能。调用不带文件扩展名的可执行文件的行为由操作系统和 PATH 变量定义。维基百科对你的问题有很好的答案 PATH (variable)

...
When a command is entered in a command shell or a system call is made by a program to execute a program, the system first searches the current working directory and then searches the path, examining each directory from left to right, looking for an executable filename that matches the command name given.
...

可执行文件后面的文件名可以是一切。因此,如果您愿意,可以致电 python demo.txt。如果文件内容对于 python 是可读的,它也会被执行。