简体   繁体   English

如何在 Windows 中执行 Python 脚本?

[英]How to execute Python scripts in Windows?

I have a simple script blah.py (using Python 2):我有一个简单的脚本 blah.py(使用 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. PATH 中的 python.exe。 Folder with blah.py also in PATH.带有 blah.py 的文件夹也在 PATH 中。
python.exe is default program to execute *.py files. python.exe 是执行 *.py 文件的默认程序。

What is the problem?问题是什么?

When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program.当你执行一个脚本而不在前面输入“python”时,你需要知道 Windows 如何调用程序的两件事。 First is to find out what kind of file Windows thinks it is:首先是找出Windows认为它是什么类型的文件:

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

Next, you need to know how Windows is executing things with that extension.接下来,您需要了解 Windows 如何使用该扩展执行操作。 It's associated with the file type "Python.File", so this command shows what it will be doing:它与文件类型“Python.File”相关联,因此此命令显示它将执行的操作:

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:所以在我的机器上,当我输入“blah.py foo”时,它会执行这个确切的命令,结果与我自己输入完整内容没有区别:

"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".如果您键入相同的内容,包括引号,那么您将获得与仅键入“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.即使 assoc 和 ftype 显示正确的信息,也可能会发生参数被剥离的情况。 What may help in that case is directly fixing the relevant registry keys for Python.在这种情况下可能有帮助的是直接修复 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/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 The registry path may vary, use python26.exe or python.exe or whichever is already in the registry. HKEY_CLASSES_ROOT\\Applications\\python.exe\\shell\\open\\command注册表路径可能会有所不同,使用python26.exepython.exe或注册表中已经存在的那个。

在此处输入图片说明 HKEY_CLASSES_ROOT\\py_auto_file\\shell\\open\\command

you should make the default application to handle python files be python.exe.您应该将处理 python 文件的默认应用程序设为 python.exe。

right click a *.py file, select "Open With" dialog.右键单击 *.py 文件,选择“打开方式”对话框。 In there select "python.exe" and check "always use this program for this file type" (something like that).在那里选择“python.exe”并选中“始终将此程序用于此文件类型”(类似的东西)。

then your python files will always be run using python.exe那么你的 python 文件将始终使用 python.exe 运行

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.此外,如果您希望无需在文件名末尾键入.py (或.pyw )即可运行 Python 脚本,则需要将.PY (或.PY;.PYW )添加到扩展名列表中在 PATHEXT 环境变量中。

In Windows 7:在 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在“系统变量”下向下滚动,直到看到 PATHEXT
left-click on PATHEXT to highlight it左键单击 PATHEXT 以突出显示它
left-click Edit...左键单击编辑...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)编辑“变量值”,使其包含;.PY (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.注意 #1:命令提示符窗口不会在关闭和重新打开的情况下看到更改。

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.注意#2: .py.pyw扩展名之间的区别在于前者在运行时打开命令提示符,而后者没有。

On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:在我的计算机上,我添加了;.PY;.PYW作为最后一个(最低优先级)扩展名,因此 PATHEXT 的“之前”和“之后”值是:

before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC之前: .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 .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:\>

How to execute Python scripts in Windows?如何在 Windows 中执行 Python 脚本?

You could install pylauncher .你可以安装pylauncher It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:它用于启动 .py、.pyw、.pyc、.pyo 文件并支持多个 Python 安装:

T\:> blah.py argument

You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:如果 PATHEXT 环境变量中有 .py、.pyw,则可以在不指定 .py 扩展名的情况下运行 Python 脚本:

T:\> blah argument

It adds support for shebang ( #! header line) to select desired Python version on Windows if you have multiple versions installed.如果您安装了多个版本,它增加了对 shebang( #!标题行)的支持,以在 Windows 上选择所需的 Python 版本。 You could use *nix-compatible syntax #! /usr/bin/env python您可以使用 *nix 兼容的语法#! /usr/bin/env python #! /usr/bin/env python . #! /usr/bin/env python

You can specify version explicitly eg, to run using the latest installed Python 3 version:您可以明确指定版本,例如,使用最新安装的 Python 3 版本运行:

T:\> py -3 blah.py argument

It should also fix your sys.argv issue as a side-effect.它还应该修复您的sys.argv问题作为副作用。

I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux).我遇到了同样的问题,但需要为 Windows 用户(来自 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.我需要将这些脚本安装在 Windows 用户机器上的适当位置,以便他们可以从命令行调用它们。 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.我遇到了一个解决方案,Continuum 的人将其用于 Anaconda 包附带的 Python 脚本——查看您的 Anaconda/Scripts 目录以获取示例。

For a Python script test , create two files: a test.bat and a test-script.py .对于 Python 脚本test ,创建两个文件: test.battest-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): 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 is your actual Python script: test-script.py是您实际的 Python 脚本:

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如果将这两个文件保留在本地目录中,则可以通过.bat文件调用 Python 脚本

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如果您将两个文件都复制到PATH上的某个位置(例如Anaconda\\Scripts ),那么您甚至可以通过省略.bat后缀来调用您的脚本

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.免责声明:我不知道发生了什么以及它是如何工作的,因此希望得到任何解释。

On Windows ,Windows 上

To run a python module without typing "python" ,在不键入 "python" 的情况下运行 python 模块

--> Right click any python(*.py) file --> 右键单击​​任何 python(*.py) 文件

--> Set the open with property to "python.exe" --> 设置打开属性为“python.exe”

--> Check the "always use this program for this file type" --> 勾选“对于此文件类型始终使用此程序”

--> Append the path of python.exe to variable environment eg append C:\\Python27 to PATH environment variable. --> 将python.exe 的路径附加到变量环境,例如将C:\\Python27 附加到PATH 环境变量。

To Run a python module without typing ".py" extension不键入“.py”扩展名的情况下运行 python 模块

--> Edit PATHEXT system variable and append ".PY" extension to the list. --> 编辑 PATHEXT 系统变量并将“.PY”扩展名附加到列表中。

Found an incredibly useful answer here : How to run different python versions in cmd? 在这里找到了一个非常有用的答案: 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.我建议使用 Python Launcher for Windows 实用程序,不久前引入了 Python 3.3。 You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.您也可以直接从作者的网站手动下载并安装它,以便与 Python 2 和 3 的早期版本一起使用。

Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (ie .py, .pyw, .pyc, and .pyo files).无论您如何获得它,安装后它都会与所有标准 Python 文件扩展名(即 .py、.pyw、.pyc 和 .pyo 文件)相关联。 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.您不仅可以在命令提示符下显式控制使用哪个版本,还可以通过在命令提示符处添加 Linux/Unix-y shebang #!/usr/bin/env pythonX 注释来逐个脚本地控制Python 脚本的开头。

As JF Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows.正如 JF Sebastian 所建议的, 适用于 Windows 的 Python Launcher是在 Windows 中启动不同版本 Python 的最佳和默认选择。 It used to be a third-party tool, but now it is officially supported since Python 3.3.它曾经是一个第三方工具,但现在从 Python 3.3 开始正式支持它。

New in version 3.3. 3.3 版中的新功能。

The Python launcher for Windows is a utility which aids in the location and execution of different Python versions.适用于 Windows 的 Python 启动器是一个实用程序,可帮助定位和执行不同的 Python 版本。 It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.它允许脚本(或命令行)指示对特定 Python 版本的偏好,并将定位和执行该版本。

This is a great tool just use it!这是一个很棒的工具,只需使用它!

Can you execute python.exe from any map?你可以从任何地图执行 python.exe 吗? If you do not, chek if you have proper values for python.exe in PATH enviroment如果没有,请检查 PATH 环境中 python.exe 的值是否正确

Are you in same directory than blah.py.您是否在与 blah.py 相同的目录中。 Check this by issuing command -> edit blah.py and check if you can open this file通过发出命令进行检查 -> 编辑 blah.py 并检查是否可以打开此文件

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) python arg意味着您调用 python.exe 并带有一些参数,python 假定这些参数是您要运行的脚本的文件名)

You can create bat file whit lines in your path map and run .bat file您可以在路径图中创建bat 文件whit 行并运行 .bat 文件

Example:例子:
In one of Path maps create blah.py.bat Edit file and put line在路径映射之一中创建blah.py.bat编辑文件并放置行

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您现在可以从任何地方运行 blah.py,因为在运行 bat 文件时不需要放置 .bat 扩展名

If that's what I understood, it's like this: 如果这就是我所理解的,就像这样:

C:\Users\(username)\AppData\Local\Programs\Python\Python(version)

COPY (not delete) python.exe and rename to py.exe and execute: 复制(不删除)python.exe并重命名为py.exe并执行:

py filename.py

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.假设文件名在同一个文件夹中,并且 Python 已经被添加到环境变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM