developer tip

Windows에서 Python 스크립트를 실행하는 방법은 무엇입니까?

optionbox 2020. 9. 3. 08:19
반응형

Windows에서 Python 스크립트를 실행하는 방법은 무엇입니까?


간단한 스크립트 blah.py (Python 2 사용)가 있습니다.

import sys
print sys.argv[1]

스크립트를 다음과 같이 실행하면 :

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

인수를 인쇄하지만 스크립트를 다음과 같이 실행하면

blah.py argument

오류 발생 :

IndexError ...

따라서 인수는 스크립트로 전달되지 않습니다.

PATH의 python.exe. blah.py가있는 폴더도 PATH에 있습니다.
python.exe는 * .py 파일을 실행하는 기본 프로그램입니다.

무엇이 문제입니까?


앞에 "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.exe하거나 사용 되거나 python.exe이미 레지스트리에있는 경로 일 수 있습니다 .

여기에 이미지 설명 입력 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command


python 파일을 처리하는 기본 응용 프로그램을 python.exe로 만들어야합니다.

* .py 파일을 마우스 오른쪽 버튼으로 클릭하고 "연결 프로그램"대화 상자를 선택합니다. 거기에서 "python.exe"를 선택하고 "이 파일 유형에 대해 항상이 프로그램 사용"을 선택하십시오 (그와 유사한 것).

그러면 파이썬 파일은 항상 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.

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:\>

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.


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.


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.


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!


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


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:

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.

참고 URL : https://stackoverflow.com/questions/1934675/how-to-execute-python-scripts-in-windows

반응형