IT

Windows 7의 명령 프롬프트에서 Python 프로그램을 어떻게 실행합니까?

lottoking 2020. 6. 4. 08:07
반응형

Windows 7의 명령 프롬프트에서 Python 프로그램을 어떻게 실행합니까?


Windows 7에서 명령 프롬프트로 Python 프로그램을 실행하는 방법을 알아 내려고 노력 중입니다 (지금까지이를 알아 내야했습니다 ...)

명령 프롬프트에 "python"을 입력하면 다음 오류가 발생합니다.

'python'은 내부 또는 외부 명령, 실행 가능한 프로그램 또는 배치 파일로 인식되지 않습니다.

: 도움을 찾을 때 내가 찾은 첫 번째 장소는이 사이트이었다 http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows .

다소 도움이되었지만 자습서는 Windows 2000 이전 버전 용으로 작성되었으므로 Windows 7 컴퓨터에는 최소한 도움이되었습니다. 나는 다음을 시도했다.

이전 버전의 Windows의 경우 가장 쉬운 방법은 C : \ AUTOEXEC.BAT> 파일을 편집하는 것입니다. AUTOEXEC.BAT에 다음과 같은 행을 추가하려고합니다.

이 파일은 컴퓨터에 존재하지 않습니다 (실수하지 않은 한).

다음으로 이것을 시도했습니다 : (여기 : Python 프로그램을 어떻게 실행합니까? )

당신의 길에 파이썬을두기

윈도우

프로그램을 실행하기 위해 운영 체제는 다양한 위치에서보고 입력 한 프로그램 / 명령의 이름을 일부 프로그램과 일치 시키려고합니다.

창에서 :

제어판> 시스템> 고급> | 환경 변수 | > 시스템 변수-> 경로

C : \ Python26; (또는 동등한). 당신이 그것을 정면에두면, 그것은 첫 번째 장소가 될 것입니다. 끝에 추가 할 수도 있습니다.

그런 다음 프롬프트를 다시 시작하고 'python'을 입력하십시오. 모두 제대로 작동하면 ">>>"프롬프트가 나타납니다.

이것은 Windows 7과 관련이 있으며 시스템 변수로 향했습니다. "C : \ Python27"값으로 "python"변수를 추가했습니다.

컴퓨터를 다시 시작한 후에도 계속 오류가 발생했습니다.

누구나이 문제를 해결하는 방법을 알고 있습니까?


C:\Python27"python"이라는 새 변수가 아니라 시스템 PATH 변수 에 추가 해야합니다.

시스템 PATH 환경 변수를 찾아 변수 ;(구분자)와 python.exe가 포함 된 디렉토리 경로 (예 :)를 추가하십시오 C:\Python27. 정확한 단계는 아래를 참조하십시오.

PATH 환경 변수는 cmd.exe"python"과 같이 명령 이름이 주어 졌을 때 Windows (및 )가 확인할 모든 위치를 나열합니다 ( 예 : 실행 파일 확장명 목록에 PATHEXT 변수를 사용). 해당 이름의 PATH에서 찾은 첫 번째 실행 파일이 시작 파일입니다.

이 변수를 변경 한 후에는 Windows를 다시 시작할 필요가 없지만 새 인스턴스 만 cmd.exe업데이트 된 PATH를 갖습니다. set PATH명령 프롬프트에 입력 하여 현재 값이 무엇인지 확인할 수 있습니다 .


Windows 7 이상에서 Python을 경로에 추가하는 정확한 단계 :

  1. 컴퓨터-> 시스템 속성 (또는 Win+Break)-> 고급 시스템 설정
  2. Environment variables...버튼을 클릭하십시오 (고급 탭에서)
  3. PATH 편집 및 ;C:\Python27끝에 추가 (Python 버전 대체)
  4. 확인을 클릭하십시오. PATH 변경 사항 은 변경 열린 명령 프롬프트에만 반영됩니다 .

Python2.7이 설치되었다고 가정

  1. 시작 메뉴로 이동

  2. "컴퓨터"를 마우스 오른쪽 버튼으로 클릭

  3. "속성"을 선택하십시오

  4. 왼쪽에 "고급 시스템 설정"이라는 링크가있는 대화 상자가 나타납니다. 클릭하세요.

  5. 시스템 속성 대화 상자에서 "환경 변수"라는 단추를 클릭하십시오.

  6. 환경 변수 대화 상자의 시스템 변수 창에서 "경로"를 찾으십시오.

  7. 끝에 "; C : \ Python27"을 추가하십시오. 세미콜론은 창에서 경로 구분 기호입니다.

  8. 확인을 클릭하고 대화 상자를 닫으십시오.

  9. 이제 새 명령 프롬프트를 열고 "python"을 입력하십시오.

작동해야합니다.


여기에서 웹과 Python 문서에서 답을 찾고 자체 테스트를 수행하여 최종적으로 Windows 스크립트 (WinXP 및 Win7)에서 Python 스크립트를 원활하게 작동시키는 데 약간의 노력이 필요했습니다. 그래서 방금 블로그에 글을 올렸고 다른 사람들에게 유용 할 수 있도록 아래에 붙여 넣습니다. 길어서 죄송합니다. 자유롭게 개선하십시오. 난 전문가가 아니야

[ UPDATE : Python 3.3에는 Windows 용 Python Launcher가 포함되어있어 기본 인터프리터 또는 py -2, py -3, py -2.7 등을 호출하기 위해 py (python 대신)를 입력 할 수 있습니다. 또한 shebang 라인도 지원합니다 스크립트 자체를 지정할 수 있습니다. 3.3 이전 버전의 경우 런처는 별도로 다운로드 할 수 있습니다. http://docs.python.org/3/whatsnew/3.3.html ]

Windows에서 편리하게 Python 스크립트 실행

어쩌면 자신의 Python 스크립트를 작성하거나 누군가가 데이터 파일로 무언가를 수행하기 위해 하나를 제공했을 수도 있습니다. Python 스크립트를 입수하여 "D : \ my scripts \ ApplyRE.py"에 저장했다고 가정 해보십시오. 다음과 같이 매개 변수를 전달하는 옵션을 사용하여 두 번 클릭하거나 어느 위치에서나 명령 행에 입력하여 편리하게 실행하려고합니다 (-o는 "출력 파일이 이미 존재하는 경우 겹쳐 쓰기"를 의미 함).

ApplyRE infile.txt outfile.txt -o

데이터 파일 "C : \ some files \ some lexicon.txt"도 있다고 가정하십시오. 가장 간단한 옵션은 파일이나 스크립트를 같은 위치로 옮기는 것이지만 지저분해질 수 있으므로 따로 보관한다고 가정 해 봅시다.

Windows가 Python 인터프리터를 찾을 수 있는지 확인

Python을 설치 한 후 python을 명령 프롬프트에 입력했는지 확인한 다음 exit ()를 입력하여 Python 인터프리터에서 돌아옵니다.

C:\>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
C:\>

이것이 작동하지 않으면 PATH 환경 변수에 "; C : \ Python32"(따옴표없이)를 추가해야합니다. 지침은 아래의 PATHEXT를 참조하십시오.

Python을 .py 및 .pyc와 연관

ApplyRE.py를 두 번 클릭하여 실행되는지 확인하십시오. (또한 Python 로고가 아이콘으로 표시되어야하며 "Python File"이라는 레이블이 붙어 있어야합니다.) 아직 완료되지 않은 경우 .py 파일을 마우스 오른쪽 단추로 클릭하고 연결 프로그램, 프로그램 선택 및 확인을 차례로 선택하십시오. "항상 사용 ..."이 연결은 편의성을 향상 시키지만 반드시 필요한 것은 아닙니다. 다음과 같이 스크립트를 실행할 때마다 "python"을 지정할 수 있습니다.

D:\my scripts>python ApplyRE.py lexicon-sample.txt -o
Running... Done.

Here's a very specific variation, which is optional unless you need to specify a different version of the interpreter.

D:\my scripts>c:\python32\python ApplyRE.py lexicon-sample.txt -o
Running... Done.

But that's a pain. Fortunately, once Python is installed, in the PATH, and associated with .py, then double-clicking a .py file or directly typing it as a command should work fine. Here, we seem to be running the script directly--it's nice and simple to run it on a sample file that's located in the "my scripts" folder along with the script.

D:\my scripts>ApplyRE.py lexicon-sample.txt -o
Running... Done.

Omitting the .py extension (editing PATHEXT)

To further reduce typing, you can tell Windows that .py (and perhaps .pyc files) are executable. To do this, right-click Computer and choose Properties, Advanced, Environment Variables, System Variables. Append ";.PY;.PYC" (without quotes) to the existing PATHEXT variable, or else create it if you're certan it doesn't exist yet. Close and reopen the command prompt. You should now be able to omit the .py (FYI, doing so would cause ApplyRE.exe or ApplyRE.bat to run instead, if one existed).

D:\my scripts>ApplyRE lexicon-sample.txt -o
Running... Done.

Adding scripts to the system PATH

If you're going to use your scripts often from the command prompt (it's less important if doing so via using BAT files), then you'll want to add your scripts' folder to the system PATH. (Next to PATHEXT you should see a PATH variable; append ";D:\my scripts" to it, without quotes.) This way you can run a script from some other location against the files in current location, like this:

C:\some files>ApplyRE "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.

Success! That's pretty much all you need to do to streamline the command-line.

Running directly without tweaking the PATH

If you're a fast typist or don't mind creating a batch file for each situation, you can specify full paths (for the script, or for the parameters) instead of tweaking PATH.

C:\some files>"d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
Running... Done.
C:\some files>d:
D:\>cd "my scripts"
D:\my scripts>ApplyRE.py "c:\some files\some lexicon.txt" "c:\some files\some lexicon OUT.txt" -o
Running... Done.

Creating shortcuts or batch files

If .py is associated with an installed Python, you can just double-click ApplyRE.py to run it, but the console may appear and disappear too quickly to read its output (or failure!). And to pass parameters, you'd need to first do one of the following. (a) Right-click and create a shortcut. Right-click the shortcut to edit properties and append parameters to Target. (b) Create a batch file--a plain text file with a distinct name such as ApplyRErun.bat. This option is probably better because you can ask it to pause so you can see the output. Here is a sample BAT file's contents, written to be located and run from c:\some files .

python "d:\my scripts\ApplyRE.py" "some lexicon.txt" "some lexicon OUT.txt" -o
pause

Advanced: appending to PYTHONPATH

This usually isn't necessary, but one other environment variable that may be relevant is PYTHONPATH. If we were to append d:\my scripts to that variable, then other Python scripts in other locations could make use of those via import statements.


Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

cmd

Go to the directory you installed Python in

cd C:\Python27

Run python and the win_add2path.py script in Tools\Scripts

python.exe Tools\Scripts\win_add2path.py

Now you can use python as a command anywhere.


You have to put the python path in the PATH variable.

In the System Variables section, you should have User Variables and System Variables. Search for the PATH variable and edit its value, adding at the end ;C:\python27.

The ; is to tell the variable to add a new path to this value, and the rest, is just to tell which path that is.

On the other hand, you can use ;%python% to add the variable you created.


You don't add any variables to the System Variables. You take the existing 'Path' system variable, and modify it by adding a semi-colon after, then c:\Python27


  • Go to the Start Menu

  • Right Click "Computer"

  • Select "Properties"

  • A dialog should pop up with a link on the left called "Advanced system settings". Click it.

  • In the System Properties dialog, click the button called "Environment Variables".

  • In the Environment Variables dialog look for "Path" under the System Variables window.

  • Add ";C:\Python27" to the end of it. The semicolon is the path separator on windows.

  • Click Ok and close the dialogs.

  • Now open up a new command prompt and type "python" or if it says error type "py" instead of "python"


first make sure u enter the path environmental variable

C:\ path %path%;C:\Python27 press Enter

C:\Python27>python file_name press Enter


So after 30 min of R&D i realized that after setup the PATH at environment variable

i.e.

" C:\Python/27; "

just restart

now open cmd :

C:> cd Python27 C:\ Python27> python.exe

USE python.exe with extension

alternative option is :

if the software is installed properly directly run Python program, your command line screen will automatically appear without cmd.

Thanks.


Just want to mention, when you do:

cd C:\Python27
python Tools\Scripts\win_add2path.py

The PATH variable in "user variables for administrator" is changed.

But you can also follow the others' answer to open:

System -> advanced system settings -> advanced -> Environment Variables,

and modify/add the variable Path in "System Variables", add ;C:\Python27 at the end of it.


Even after going through many posts, it took several hours to figure out the problem. Here is the detailed approach written in simple language to run python via command line in windows.

1. Download executable file from python.org
Choose the latest version and download Windows-executable installer. Execute the downloaded file and let installation complete.

2. Ensure the file is downloaded in some administrator folder

  1. Search file location of Python application.
  2. Right click on the .exe file and navigate to its properties. Check if it is of the form, "C:\Users....". If NO, you are good to go and jump to step 3. Otherwise, clone the Python37 or whatever version you downloaded to one of these locations, "C:\", "C:\Program Files", "C:\Program Files (x86)".

3. Update the system PATH variable This is the most crucial step and there are two ways to do this:- (Follow the second one preferably)

1. MANUALLY
- Search for 'Edit the system Environment Variables' in the search bar.(WINDOWS 10)
- In the System Properties dialog, navigate to "Environment Variables".
- In the Environment Variables dialog look for "Path" under the System Variables window. (# Ensure to click on Path under bottom window named System Variables and not under user variables)
- Edit the Path Variable by adding location of Python37/ PythonXX folder. I added following line:-
" ;C:\Program Files (x86)\Python37;C:\Program Files (x86)\Python37\Scripts "
- Click Ok and close the dialogs.

2. SCRIPTED
- Open the command prompt and navigate to Python37/XX folder using cd command.
- Write the following statement:-
"python.exe Tools\Scripts\win_add2path.py"

You can now use python in the command prompt:)
1. Using Shell
Type python in cmd and use it.
2. Executing a .py file
Type python filename.py to execute it.


in powershell enter the following:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

close and open the powershell and try again. this should solve your problem.


You need to edit the environment variable named PATH, and add ;c:\python27 to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH).

Alternately, you can just type

c:\python27\python

at the command prompt without having to modify any environment variables at all.


On Windows you use C:\Python27\python.exe instead of python.

If you add C:\Python27 to your path, you can shorten it to just python.exe, but you do not need to do this.


Modify the PATH variable too and append ;%python% otherwise the executable can not be found.


First install the Python into your windows by using this url and then add path variable as

c:\python27

Use this PATH in Windows 7:

C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\;

I also found the same problem even though i've added the path in the environment variable. Finally, I put my "C:\Python27" in the FRONT part of the "PATH" in environment variable and after restarting the cmd, it works!!! I hope this can help.


For Windows 10 & Python 3.5.1 users:

While installing Python on Windows 10, please don't forget to check the "Add to cmd prompt" option before hitting the "Install". This would help in easily access python from cmd.

If the option was not checked, then please use Set Path in cmd to see if it is available as executables or not. If not, Navigate to Start >> Control Panel >> System and Security >> System >> Advanced System Settings >> Advanced >> Environment Variables.. >> Select PATH from System Variables and Edit it. Then copy "C:\Python35\cmd" in the new line. After this please add .PY to PATHEXT in the same procedure.

Also please check if Start >> Control Panel >> System and Security >> System >> Advanced System Settings >> Advanced >> Environment Variables.. >> User variables from Username >> PATH is containing these two lines - "C:\Users\Username\AppData\Local\Programs\Python\Python35-32\Scripts\" & "C:\Users\Username\AppData\Local\Programs\Python\Python35-32\". Else please add them manually.

Ref: https://docs.python.org/3/using/windows.html


Goto the Start Menu Right Click "Computer" Select "Properties" A dialog should pop up with a link on the left called "Advanced system settings". Click it. In the System Properties dialog, click the button called "Environment Variables". In the Environment Variables dialog look for "Path" under the System Variables window. Add ";C:\Python27" to the end of it. The semicolon is the path separator on windows. Click Ok and close the dialogs. Now open up a new command prompt and type "python"

If still the problem persists then type "py" instead of "python" in command prompt. might help!!!!


press start button then type cmd. - Note you will need to run the command prompt as 'Adminstrator'.

write setx -m path "%path%;C:\Python27" then press enter.

[here -m for giving accessing permission to all users and in Python27 27 is version 2.7]

%path%; will prevent the original value from destroying. C:\Python27 will be appended to the current Path value.

that's it,you are done.


For windows 8, just type "py".

참고URL : https://stackoverflow.com/questions/4621255/how-do-i-run-a-python-program-in-the-command-prompt-in-windows-7

반응형