如何在Windows中执行Python脚本?

发布于 2024-08-15 20:41:05 字数 428 浏览 6 评论 0原文

我有一个简单的脚本 blah.py (使用 Python 2):

import sys
print sys.argv[1]

如果我通过以下方式执行脚本:

python c:/..../blah.py argument

它会打印参数,但如果我通过以下方式执行脚本:

blah.py argument

会发生错误:

索引错误...

因此参数不会传递给脚本。

路径中的 python.exe。包含 blah.py 的文件夹也在 PATH 中。
python.exe 是执行 *.py 文件的默认程序。

问题是什么?

I have a simple script blah.py (using Python 2):

import sys
print sys.argv[1]

If I execute my script by:

python c:/..../blah.py argument

It prints argument but if I execute script by:

blah.py argument

error occurs:

IndexError...

So arguments do not pass to script.

python.exe in PATH. Folder with blah.py also in PATH.
python.exe is default program to execute *.py files.

What is the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

纸伞微斜 2024-08-22 20:41:05

当你执行一个脚本而不在前面输入“python”时,你需要了解有关Windows如何调用该程序的两件事。首先是找出 Windows 认为它​​是什么类型的文件:

    C:\>assoc .py
    .py=Python.File

接下来,您需要知道 Windows 如何执行带有该扩展名的文件。它与文件类型“Python.File”相关联,因此该命令显示了它将执行的操作:

    C:\>ftype Python.File
    Python.File="c:\python26\python.exe" "%1" %*

因此,在我的机器上,当我输入“blah.py foo”时,它将执行这个确切的命令,结果与如果我自己输入了完整的内容:

    "c:\python26\python.exe" "blah.py" foo

如果您输入相同的内容(包括引号),那么您将得到与仅输入“blah.py foo”时相同的结果。现在您可以自己解决剩下的问题了。

(或者在您的问题中发布更多有用的信息,例如您在控制台中看到的内容的实际剪切和粘贴副本。请注意,执行此类操作的人的问题会被投票通过,他们会获得声誉积分,并且更多人会这样做可能会帮助他们得到好的答案。)

来自评论:

即使 assoc 和 ftype 显示正确的信息,也可能会发生参数被剥离的情况。在这种情况下,可能有帮助的是直接修复 Python 的相关注册表项。 将密钥设置

HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command

为:

"C:\Python26\python26.exe" "%1" %*

以前可能缺少 %*。同样,设置

 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

为相同的值。请参阅 http://eli .thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

python.exe 的示例注册表设置
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command 注册表路径可能会有所不同,请使用 python26.exepython.exe 或任何一个已经在注册表中了。

输入图像描述这里
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:

    C:\>assoc .py
    .py=Python.File

Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:

    C:\>ftype Python.File
    Python.File="c:\python26\python.exe" "%1" %*

So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:

    "c:\python26\python.exe" "blah.py" foo

If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.

(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)

Brought In From Comments:

Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the

HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command

key to:

"C:\Python26\python26.exe" "%1" %*

Likely, previously, %* was missing. Similarly, set

 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

example registry setting for python.exe
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.

enter image description here
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

浪漫人生路 2024-08-22 20:41:05

您应该将处理 python 文件的默认应用程序设置为 python.exe。

右键单击 *.py 文件,选择“打开方式”对话框。在那里选择“python.exe”并选中“始终将此程序用于此文件类型”(类似的内容)。

那么你的 python 文件将始终使用 python.exe 运行

you should make the default application to handle python files be python.exe.

right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).

then your python files will always be run using python.exe

爱你是孤单的心事 2024-08-22 20:41:05

此外,如果您希望能够运行 python 脚本而无需在文件名末尾键入 .py (或 .pyw),则需要添加 < code>.PY (或 .PY;.PYW)到 PATHEXT 环境变量中的扩展名列表。

在 Windows 7 中:

右键单击“计算机”
左键单击“属性”
左键单击高级系统设置
左键单击“高级”选项卡
左键单击环境变量...
在“系统变量”下向下滚动,直到看到 PATHEXT
左键单击 PATHEXT 以突出显示它
左键单击编辑...
编辑“变量值”,使其包含 ;.PY (End 键将跳到末尾)
左键单击“确定”
左键单击“确定”
左键单击“确定”

注意#1:命令提示符窗口不会看到未关闭并重新打开的更改。

注意 #2:.py.pyw 扩展之间的区别在于前者在运行时打开命令提示符,而后者则不会。

在我的计算机上,我添加了 ;.PY;.PYW 作为最后(最低优先级)扩展名,因此 PATHEXT 的“之前”和“之后”值为:

之前:.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

以下是一些指导性命令:

C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*

C:\>assoc .pyw
.pyw=Python.NoConFile

C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*

C:\>type c:\windows\helloworld.py
print("Hello, world!")  # always use a comma for direct address

C:\>helloworld
Hello, world!

C:\>

Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.

In Windows 7:

right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables...
under "system variables" scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK

Note #1: command-prompt windows won't see the change w/o being closed and reopened.

Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.

On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:

before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

Here are some instructive commands:

C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*

C:\>assoc .pyw
.pyw=Python.NoConFile

C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*

C:\>type c:\windows\helloworld.py
print("Hello, world!")  # always use a comma for direct address

C:\>helloworld
Hello, world!

C:\>
吾家有女初长成 2024-08-22 20:41:05

如何在Windows中执行Python脚本?

您可以安装 pylauncher。它用于启动 .py、.pyw、.pyc、.pyo 文件并支持多个 Python 安装:

T\:> blah.py argument

如果 PATHEXT 环境变量中有 .py、.pyw,则无需指定 .py 扩展名即可运行 Python 脚本:

T:\> blah argument

它增加了支持如果您安装了多个版本,则可以使用 shebang(#! 标题行)在 Windows 上选择所需的 Python 版本。您可以使用 *nix 兼容语法 #! /usr/bin/env python

您可以显式指定版本,例如使用最新安装的 Python 3 版本运行:

T:\> py -3 blah.py argument

它还应该修复您的 sys.argv 问题作为副作用。

How to execute Python scripts in Windows?

You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:

T\:> blah.py argument

You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:

T:\> blah argument

It adds support for shebang (#! header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python.

You can specify version explicitly e.g., to run using the latest installed Python 3 version:

T:\> py -3 blah.py argument

It should also fix your sys.argv issue as a side-effect.

英雄似剑 2024-08-22 20:41:05

我遇到了同样的问题,但需要为 Windows 用户(来自 Linux)打包我的代码。
我的包包含许多带有命令行选项的脚本。

我需要将这些脚本安装在 Windows 用户计算机上的适当位置,以便他们可以从命令行调用它们。
由于该软件包被认为是用户友好的,因此要求我的用户更改其注册表以运行这些脚本是不可能的。

我遇到了 Continuum 的人员使用 Anaconda 包附带的 Python 脚本的解决方案 - 请查看您的 Anaconda/Scripts 目录以获取示例。

对于 Python 脚本 test,创建两个文件:test.battest-script.py

test.bat 如下所示(Anaconda\Scripts 中的 .bat 文件使用相对的调用 python.exe我根据自己的目的进行了调整的路径):

@echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*

test-script.py 是您实际的 Python 脚本:

import sys
print sys.argv

如果您将这两个文件保留在本地目录中,您可以通过 .bat 调用您的 Python 脚本 文件

test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']

如果您将这两个文件复制到 PATH 上的某个位置(例如 Anaconda\Scripts),那么您甚至可以通过离开来调用脚本输出 .bat 后缀

test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']

免责声明:我不知道发生了什么以及它是如何工作的,因此希望得到任何解释。

I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux).
My package contains a number of scripts with command line options.

I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line.
As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.

I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.

For a Python script test, create two files: a test.bat and a test-script.py.

test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):

@echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*

test-script.py is your actual Python script:

import sys
print sys.argv

If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing

test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']

If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix

test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']

Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.

长伴 2024-08-22 20:41:05

Windows上,

运行 python 模块而不输入“python”

-->右键单击任意 python(*.py) 文件

-->将 open with 属性设置为“python.exe”

-->勾选“对于该文件类型始终使用该程序”

-->将 python.exe 的路径追加到变量环境中,例如append
C:\Python27 到 PATH 环境变量。

在不输入“.py”扩展名的情况下运行 python 模块

-->编辑 PATHEXT 系统变量并将“.PY”扩展名附加到列表中。

On Windows,

To run a python module without typing "python",

--> Right click any python(*.py) file

--> Set the open with property to "python.exe"

--> Check the "always use this program for this file type"

--> Append the path of python.exe to variable environment e.g. append
C:\Python27 to PATH environment variable.

To Run a python module without typing ".py" extension

--> Edit PATHEXT system variable and append ".PY" extension to the list.

爱给你人给你 2024-08-22 20:41:05

你可以从任何地图执行 python.exe 吗?
如果没有,请检查 PATH 环境中的 python.exe 是否有正确的值,

是否与 blah.py 位于同一目录中。通过发出命令 -> 检查这一点编辑 blah.py 并检查是否可以打开此文件

编辑:

在这种情况下则不能。 (python arg 表示您调用 python.exe,其中包含一些参数,Python 假定这些参数是您要运行的脚本的文件名)

您可以在路径中创建 bat 文件 白色行映射并运行 .bat 文件

示例:
在路径映射之一中创建 blah.py.bat
编辑文件并放置行

python C:\Somedir\blah.py

您现在可以从任何地方运行blah.py,因为运行bat文件时不需要放置.bat扩展名

Can you execute python.exe from any map?
If you do not, chek if you have proper values for python.exe in PATH enviroment

Are you in same directory than blah.py. Check this by issuing command -> edit blah.py and check if you can open this file

EDIT:

In that case you can not. (python arg means that you call python.exe whit some parameters which python assume that is filename of script you want to run)

You can create bat file whit lines in your path map and run .bat file

Example:
In one of Path maps create blah.py.bat
Edit file and put line

python C:\Somedir\blah.py

You can now run blah.py from anywere, becuase you do not need to put .bat extention when running bat files

_畞蕅 2024-08-22 20:41:05

此处找到了一个非常有用的答案:如何在cmd中运行不同的python版本?

我建议使用不久前在 Python 3.3 中引入的 Windows 实用程序的 Python Launcher。您还可以直接从作者的网站手动下载并安装它,以便与早期版本的 Python 2 和 3 一起使用。

无论您如何获取它,安装后它都会将自己与所有标准 Python 文件扩展名(即 .py、.pyw、.pyc 和 .pyo 文件)相关联。您不仅可以在命令提示符下显式控制使用哪个版本,还可以通过在脚本中添加 Linux/Unix-y shebang #!/usr/bin/env pythonX 注释来逐个脚本地控制使用哪个版本。 Python 脚本的开头。

正如 JF Sebastian 所建议的,Python 启动器Windows 是在 Windows 中启动不同版本的 Python 的最佳默认选择。它曾经是一个第三方工具,但现在从Python 3.3开始正式支持。

3.3 版本中的新增功能。

Windows 的 Python 启动器是一个实用程序,可帮助定位和执行不同的 Python 版本。它允许脚本(或命令行)指示对特定 Python 版本的偏好,并将定位并执行该版本。

这是一个很棒的工具,只需使用它!

Found an incredibly useful answer here: How to run different python versions in cmd?

I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.

Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.

As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.

New in version 3.3.

The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.

This is a great tool just use it!

风启觞 2024-08-22 20:41:05

只需运行命令:

C:>python .\file_name.py

假设文件名位于同一文件夹中,并且 Python 已添加到环境变量中。

Simply run the command:

C:>python .\file_name.py

Assuming the file name is within same folder and Python has already been added to environment variables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文