7

我是编程新手,Python 是我的第一语言。我已将 Python 添加到我的路径中,但是当我使用命令提示符时,我不必在myscript.py之前添加 python,这与我见过的许多教程相反。这是一个例子:

C:\User\MyName>Welcome.py
Welcome to Python
Python is fun

当我输入'python'时,出现后续错误:

C:\User\MyName>python Welcome.py
python: can't open file 'Welcome.py': [Errno 2] No such file or directory

我真的需要'python'吗?提前致谢!

4

3 回答 3

4

如果您按照Windows 上的 Python 常见问题解答,似乎标准 Python 安装程序已经冒昧地将文件与打开命令关联.py..\..\Python\python.exe "%1" %*到.

如何使 Python 脚本可执行?

在 Windows 上,标准 Python 安装程序已经将 .py 扩展名与文件类型 (Python.File) 相关联,并为该文件类型提供运行解释器的打开命令 (D:\Program Files\Python\python.exe "%1" %*)。这足以使脚本在命令提示符下作为“foo.py”执行。如果您希望能够通过简单地键入不带扩展名的“foo”来执行脚本,则需要将 .py 添加到 PATHEXT 环境变量中。

谁会想!这不是四年前我第一次在我的 Windows 机器上安装 Python 时的方式。

于 2013-07-19T23:23:44.330 回答
1

When you install python on windows with a regular installer, .py files are associated with the python.exe you installed. When you type Welcome.py, Windows searches the local directory and then all paths in the PATH variable for a program called Welcome.py and runs it via python. Since this worked for you, it means that Welcome.py is somewhere on your path or in your local directory.

You can figure out your file associations with the assoc .py and ftype Python.File commands. The echo %PATH% and echo %PATHEXT% commands are also useful.

When you type python Welcome.py, Windows searches all paths in the PATH variable for a program that starts with 'python' and ends with an extension in PATHEXT. It finds 'python.exe' and runs it. Python in turn looks for a script called Welcome.py in the current directory. Since this didn't work for you, it means that Welcome.py is not in your local directory. It would have worked if you had given the right path to Welcome.py.

You can find out where Welcome.py is with the (not surprisingly) where Welcome.py command.

If you only have a single python installation, there is no need to call python myscript.py ....

于 2013-07-19T23:58:30.557 回答
1

是和不是。
这实际上取决于脚本的编写方式。

在大多数 unix 系统(Linux、Mac OS)上,您可以包含#!/bin/python在脚本的顶部(作为第一行),因此只需在命令行上调用文件名即可执行它。第一行告诉 shell 这个文件包含一个 python 程序。然后,shell 使用 python 解释器来执行文件(翻译:它将你翻译$ Welcome.py$ /bin/python Welcome.py<- 请注意,python 被显式调用,并且它与文件第一行的路径相同)。

想必,Windows 操作系统也可以用同样的方式进行指令,虽然我自己从来没有做过,也没有很努力地尝试过(大约 5 年前我离开了 Windows)。这就是为什么您需要显式调用python.
调用 python 会告诉操作系统:“嘿!打开名为 python 的程序并告诉它运行文件Welcome.py”。这正是该命令/bin/python Welcome.py在 unix 系统上所做的

于 2013-07-19T23:14:31.813 回答