Загрузить PDF
Загрузить PDF
Из этой статьи вы узнаете, как открыть файл Python при помощи встроенной Командной строки на компьютере под управлением Windows. В большинстве случаев это можно сделать без каких-либо проблем — главное, чтобы на вашем компьютере был установлен Python. Если вы установили старую версию Python или использовали пользовательские настройки в ходе установки, из-за которых команда «python» не была добавлена в список переменных «Path» на компьютере, вам придется добавить Python в список переменных «Path», чтобы иметь возможность запускать файл Python через командную строку.
-
1
Перейдите к папке с файлом Python. Найдите файл Python, который хотите открыть в Командной строке.
- Если вам уже известен путь к файлу Python, который вы хотите открыть, перейдите к разделу об открытии файла в Командной строке..
-
2
Выберите файл Python. Нажмите один раз на файл Python, путь к которому вы хотите узнать.
-
3
Щелкните правой кнопкой мыши по файлу Python. Появится выпадающее меню.
-
4
Выберите Свойства из выпадающего меню. Откроется окно свойств.
-
5
Обратите внимание на значение в строке «Расположение». Адрес папки (или «путь») справа от пункта «Расположение» — это именно то, что вам нужно ввести в Командную строку, чтобы перейти к каталогу, в котором хранится файл Python.
- Чтобы скопировать расположение, его необходимо выделить (зажмите и перетащите указатель мыши по значению в строке «Расположение»), а затем нажать Ctrl+C.
Реклама
-
1
Откройте меню «Пуск»
. Щелкните по логотипу Windows в нижнем левом углу экрана. Появится меню «Пуск».
-
2
Найдите Командную строку, введя cmd.
-
3
Нажмите на
Командная строка в верхней части меню «Пуск», чтобы открыть Командную строку.
-
4
Перейдите к расположению файла Python. Введите cd и нажмите пробел, после чего введите адрес «Расположение» файла Python и нажмите ↵ Enter.
- К примеру, чтобы открыть файл Python в папке с именем «Файлы» на рабочем столе, вам нужно ввести cd desktop/Файлы.
- Если вы скопировали путь к файлу, введите cd и нажмите пробел, после чего нажмите Ctrl+V, чтобы вставить путь.
-
5
Введите команду «python» и имя файла. Введите python файл.py, где файл — это имя файла Python.
- К примеру, если файл Python называется «script», введите python script.py.
- Если в имени файла Python есть один или несколько пробелов, окружите имя и расширение файла кавычками (например, python "my script.py").
-
6
Нажмите ↵ Enter, чтобы запустить команду и открыть файл Python через установленную на компьютере программу Python.
- Если после нажатия клавиши «Enter» вы столкнетесь с ошибкой, сообщающей, что
'python' не распознается как внутренняя или внешняя команда
, вам нужно будет добавить Python в список «PATH», прежде чем вернуться к этой части.
Реклама
- Если после нажатия клавиши «Enter» вы столкнетесь с ошибкой, сообщающей, что
-
1
Включите отображение скрытых папок. Поскольку одна из папок, в которой находится установочный каталог Python, скорее всего, скрыта, вам придется ее отобразить, прежде чем продолжить:
- Откройте Проводник
.
- Щелкните по вкладке Вид.
- Установите флажок в поле «Скрытые элементы».
- Откройте Проводник
-
2
Перейдите в папку, в которой установлен Python. Python иногда размещают в папку «C:Python27», но если вы установили самую последнюю версию Python, используя настройки по умолчанию, программа будет спрятана в скрытой папке. Скопируйте правильный путь к файлу, выполнив следующие действия:
- Нажмите на Этот компьютер в левой части Проводника.
- Дважды щелкните по своему жесткому диску в разделе «Устройства и диски».
- Прокрутите вниз и дважды щелкните по папке «Пользователи».
- Дважды щелкните по папке с вашим именем пользователя.
- Прокрутите вниз и дважды щелкните по папке «AppData».
- Дважды щелкните по папке «Local».
- Прокрутите вниз и дважды щелкните по папке «Programs».
- Дважды щелкните по папке «Python».
- Дважды щелкните по папке «Python» с номером версии (например, «Python36»).
-
3
Скопируйте путь к папке Python. Нажмите на адресную строку в верхней части Проводника, чтобы выделить ее содержимое, а затем нажмите Ctrl+C, чтобы скопировать выделенный адрес.
-
4
Откройте контекстное меню. Для этого щелкните правой кнопкой мыши по иконке «Пуск»
. После этого появится всплывающее меню.
- Всплывающее контекстное меню можно также открыть, нажав ⊞ Win+X.
-
5
Нажмите на Система во всплывающем меню. Откроется новое окно.
-
6
Нажмите на Сведения о системе. Это ссылка в правом верхнем углу окна. Откроется окно «Система».
-
7
Нажмите на ссылку Дополнительные параметры системы в левой верхней части окна «Система». Появится еще одно окно.
-
8
Нажмите на Переменные среды в правом нижнем углу всплывающего окна.
-
9
Найдите заголовок «Path» на панели «Переменные среды пользователя». Это окно находится вверху окна «Переменные среды».
- Возможно, вам придется прокрутить курсор вверх или вниз над панелью «Переменные среды пользователя», чтобы найти переменную «Path».
-
10
Дважды щелкните по заголовку «Path». Откроется всплывающее окно.
-
11
Нажмите на Создать в правой части окна. Посередине окна откроется текстовое поле.
-
12
Вставьте скопированный путь. Для этого нажмите Ctrl+V. Скопированный путь появится в текстовом поле посередине окна.
-
13
Нажмите OK в трех открытых окнах. Таким образом вы сохраните изменения и закроете окно «Path», окно «Переменные среды» и окно «Свойства системы».
Реклама
Об этой статье
Эту страницу просматривали 120 843 раза.
Была ли эта статья полезной?
Download Article
Download Article
Whether you’re writing Python code on your Windows PC or just want to use existing Python scripts, it’ll be helpful to learn how to run code from the Command Prompt. Running Python code is easy—you’ll just need to have Python installed. This wikiHow article will walk you through opening a Python file from Command Prompt, and teach you how to fix the common «python is not recognized as an internal or external command» error.
-
1
Go to the Python file’s location. Find the Python file that you want to open in Command Prompt.
- If you already know the folder path to the Python file you want to open, skip ahead to opening the file in Command Prompt.
-
2
Select the Python file. Click once the Python file for which you want to see the folder path.
Advertisement
-
3
Right-click the Python file. Doing so prompts a drop-down menu to appear.
-
4
Click Properties. It’s in the drop-down menu. The properties window will open.
-
5
Note the «Location» value. The folder address (or «path») to the right of the «Location» heading is what you’ll need to enter into Command Prompt when switching to the directory in which your Python file is stored.
- You can copy the location by highlighting it (click and drag your mouse across the «Location» value) and then pressing Ctrl+C.
Advertisement
-
1
Open Start
. Click the Windows logo in the bottom-left corner of the screen. The Start menu will pop up.
-
2
Search for Command Prompt. Type in cmd to do so.
-
3
-
4
Switch to your Python file’s directory. Type cd and a space, then type in the «Location» address for your Python file and press ↵ Enter.
- For example, to open a Python file in a folder named «Files» on your Desktop, you would enter cd desktop/Files here.
- If you copied the path to the file, you can type in cd and a space and then press Ctrl+V to paste in the path.
-
5
Enter the «python» command and your file’s name. Type in python file.py where file is your Python file’s name.
- For example, if your Python file is named «script», you would type in python script.py here.
- If your Python file has one or more spaces in its name, you’ll place quotation marks around the file name and extension (e.g., python "my script.py").
-
6
Press ↵ Enter. Doing so runs your command and opens your Python file via your computer’s installed Python program.
- If you encounter an error that says
'python' is not recognized as an internal or external command
after pressing Enter, you’ll need to add Python to the PATH list before retrying this part.
- If you encounter an error that says
Advertisement
-
1
Enable viewing for hidden folders. Since one of the folders that contains your Python installation folder is most likely hidden, you’ll have to unhide it before proceeding:
- Open File Explorer
.
- Click the View tab.
- Check the «Hidden items» box.
- Open File Explorer
-
2
Navigate to your Python folder. In some cases, the Python path is «C:Python27»; however, if you’ve installed the most recent version of Python using the default settings, it’s tucked away in a hidden folder. You can copy the proper file path by doing the following:
- Click This PC on the left side of the File Explorer.
- Double-click your hard drive in the «Devices and drives» section.
- Scroll down and double-click the «Users» folder.
- Double-click the folder with your username on it.
- Scroll down and double-click «AppData».
- Double-click «Local».
- Scroll down and double-click «Programs».
- Double-click the «Python» folder.
- Double-click the Python folder with your preferred version number (e.g., «Python36»).
-
3
Copy the path to the Python folder. Click once the address bar at the top of the File Explorer to highlight its contents, then press Ctrl+C to copy the highlighted address.
-
4
Open the Power User menu. Right-click the Start
icon to do so. You should see a pop-up menu appear.
- You can also press ⊞ Win+X to open the Power User pop-up menu.
-
5
Click System. It’s in the pop-up menu. A new window will open.
-
6
Click System info. This is a link in the upper-right corner of the window. Doing so opens the System Information window.
-
7
Click the Advanced system settings link. You’ll see this in the upper-left side of the System Information window. Yet another window will pop up.
-
8
Click Environment Variables…. It’s in the bottom-right corner of the pop-up window.
-
9
Find the «Path» heading in the «User variables» pane. This window is at the top of the Environment Variables window.
- You may have to scroll up or down with your mouse cursor hovering over the «User variables» pane to find the «Path» variable.
-
10
Double-click the «Path» heading. Doing so opens a pop-up window.
-
11
Click New. It’s on the right side of the window. A text field will open in the middle of the window.
-
12
Paste in your copied path. Press Ctrl+V to do so. Your copied path will appear in the text field in the middle of the window.
-
13
Click OK on the three open windows. This will save your changes and close the «Path» window, the «Environmental Variables» window, and the «System Properties» window.
Advertisement
Add New Question
-
Question
I want to create a shortcut that executes the utility «ptpython,» running in the cmd prompt. The shortcut I have points to the directory containing «ptpython.exe» file but it does not execute it.
It sounds like ptpython.exe is a command-line utility, meaning it will only start if you execute it from a DOS window — you can’t create a shortcut for it directly. You can probably create a shortcut to cmd.exe, though (the DOS window) and pass it the ptpython.exe file as a parameter. Something like «cmd.exe /c ptpython.exe» should work, or if this disappears in the end, try with /k (instead of /c).
-
Question
Does this work on Windows 7?
Yes. The directions to access the environment variables would be slightly different, as there is no «Power User» menu in Windows 7. Instead: 1. Press the Windows key and R to open the Run dialog. 2. Enter «sysdm.cpl». 3. Click the «Advanced» tab of the System Properties Window. 4. Click the «Environmental variables». Most everything else would work as described even on Windows 95 (if there’s a version of Python for Windows 95).
-
Question
After opening the Command Prompt and navigation to the directory in which the py file exists and opening Python, not able to run the file using python file_name.py. It says that the syntax is wrong.
That sounds like a problem with the file you’re trying to run. Make sure you are using the right version of Python for it (version 2 or 3, usually).
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 718,311 times.
Is this article up to date?
Download Article
Download Article
Whether you’re writing Python code on your Windows PC or just want to use existing Python scripts, it’ll be helpful to learn how to run code from the Command Prompt. Running Python code is easy—you’ll just need to have Python installed. This wikiHow article will walk you through opening a Python file from Command Prompt, and teach you how to fix the common «python is not recognized as an internal or external command» error.
-
1
Go to the Python file’s location. Find the Python file that you want to open in Command Prompt.
- If you already know the folder path to the Python file you want to open, skip ahead to opening the file in Command Prompt.
-
2
Select the Python file. Click once the Python file for which you want to see the folder path.
Advertisement
-
3
Right-click the Python file. Doing so prompts a drop-down menu to appear.
-
4
Click Properties. It’s in the drop-down menu. The properties window will open.
-
5
Note the «Location» value. The folder address (or «path») to the right of the «Location» heading is what you’ll need to enter into Command Prompt when switching to the directory in which your Python file is stored.
- You can copy the location by highlighting it (click and drag your mouse across the «Location» value) and then pressing Ctrl+C.
Advertisement
-
1
Open Start
. Click the Windows logo in the bottom-left corner of the screen. The Start menu will pop up.
-
2
Search for Command Prompt. Type in cmd to do so.
-
3
-
4
Switch to your Python file’s directory. Type cd and a space, then type in the «Location» address for your Python file and press ↵ Enter.
- For example, to open a Python file in a folder named «Files» on your Desktop, you would enter cd desktop/Files here.
- If you copied the path to the file, you can type in cd and a space and then press Ctrl+V to paste in the path.
-
5
Enter the «python» command and your file’s name. Type in python file.py where file is your Python file’s name.
- For example, if your Python file is named «script», you would type in python script.py here.
- If your Python file has one or more spaces in its name, you’ll place quotation marks around the file name and extension (e.g., python "my script.py").
-
6
Press ↵ Enter. Doing so runs your command and opens your Python file via your computer’s installed Python program.
- If you encounter an error that says
'python' is not recognized as an internal or external command
after pressing Enter, you’ll need to add Python to the PATH list before retrying this part.
- If you encounter an error that says
Advertisement
-
1
Enable viewing for hidden folders. Since one of the folders that contains your Python installation folder is most likely hidden, you’ll have to unhide it before proceeding:
- Open File Explorer
.
- Click the View tab.
- Check the «Hidden items» box.
- Open File Explorer
-
2
Navigate to your Python folder. In some cases, the Python path is «C:Python27»; however, if you’ve installed the most recent version of Python using the default settings, it’s tucked away in a hidden folder. You can copy the proper file path by doing the following:
- Click This PC on the left side of the File Explorer.
- Double-click your hard drive in the «Devices and drives» section.
- Scroll down and double-click the «Users» folder.
- Double-click the folder with your username on it.
- Scroll down and double-click «AppData».
- Double-click «Local».
- Scroll down and double-click «Programs».
- Double-click the «Python» folder.
- Double-click the Python folder with your preferred version number (e.g., «Python36»).
-
3
Copy the path to the Python folder. Click once the address bar at the top of the File Explorer to highlight its contents, then press Ctrl+C to copy the highlighted address.
-
4
Open the Power User menu. Right-click the Start
icon to do so. You should see a pop-up menu appear.
- You can also press ⊞ Win+X to open the Power User pop-up menu.
-
5
Click System. It’s in the pop-up menu. A new window will open.
-
6
Click System info. This is a link in the upper-right corner of the window. Doing so opens the System Information window.
-
7
Click the Advanced system settings link. You’ll see this in the upper-left side of the System Information window. Yet another window will pop up.
-
8
Click Environment Variables…. It’s in the bottom-right corner of the pop-up window.
-
9
Find the «Path» heading in the «User variables» pane. This window is at the top of the Environment Variables window.
- You may have to scroll up or down with your mouse cursor hovering over the «User variables» pane to find the «Path» variable.
-
10
Double-click the «Path» heading. Doing so opens a pop-up window.
-
11
Click New. It’s on the right side of the window. A text field will open in the middle of the window.
-
12
Paste in your copied path. Press Ctrl+V to do so. Your copied path will appear in the text field in the middle of the window.
-
13
Click OK on the three open windows. This will save your changes and close the «Path» window, the «Environmental Variables» window, and the «System Properties» window.
Advertisement
Add New Question
-
Question
I want to create a shortcut that executes the utility «ptpython,» running in the cmd prompt. The shortcut I have points to the directory containing «ptpython.exe» file but it does not execute it.
It sounds like ptpython.exe is a command-line utility, meaning it will only start if you execute it from a DOS window — you can’t create a shortcut for it directly. You can probably create a shortcut to cmd.exe, though (the DOS window) and pass it the ptpython.exe file as a parameter. Something like «cmd.exe /c ptpython.exe» should work, or if this disappears in the end, try with /k (instead of /c).
-
Question
Does this work on Windows 7?
Yes. The directions to access the environment variables would be slightly different, as there is no «Power User» menu in Windows 7. Instead: 1. Press the Windows key and R to open the Run dialog. 2. Enter «sysdm.cpl». 3. Click the «Advanced» tab of the System Properties Window. 4. Click the «Environmental variables». Most everything else would work as described even on Windows 95 (if there’s a version of Python for Windows 95).
-
Question
After opening the Command Prompt and navigation to the directory in which the py file exists and opening Python, not able to run the file using python file_name.py. It says that the syntax is wrong.
That sounds like a problem with the file you’re trying to run. Make sure you are using the right version of Python for it (version 2 or 3, usually).
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 718,311 times.
Is this article up to date?
It has taken me some effort looking for answers here, on the web, and and in the Python documentation, and testing on my own, to finally get my Python scripts working smoothly on my Windows machines (WinXP and Win7). So, I just blogged about it and am pasting that below in case it’s useful to others. Sorry it’s long, and feel free to improve it; I’m no expert.
[UPDATE: Python 3.3 now includes the Python Launcher for Windows, which allows you to type py (rather than python) to invoke the default interpreter, or py -2, py -3, py -2.7, etc. It also supports shebang lines, allowing the script itself to specify. For versions prior to 3.3, the launcher is available as a separate download.
http://docs.python.org/3/whatsnew/3.3.html
]
Running Python scripts conveniently under Windows
Maybe you’re creating your own Python scripts, or maybe someone has given you one for doing something with your data files. Say you’ve acquired a Python script and have saved it to «D:my scriptsApplyRE.py». You want to run it conveniently by either double-clicking it or typing it into the command line from any location, with the option of passing parameters to it like this (-o means «overwrite the output file if it already exists»):
ApplyRE infile.txt outfile.txt -o
Say you also have a data file, «C:some filessome lexicon.txt». The simplest option is to move the file or the script so they’re in the same location, but that can get messy, so let’s assume that they’ll stay separate.
Making sure Windows can find the Python interpreter
After installing Python, verify that typing python into a command prompt works (and then type exit() to get back out of the Python interpreter).
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:>
If this doesn’t work, you’ll need to append something like «;C:Python32» (without quotes) to the PATH environment variable. See PATHEXT below for instructions.
Associating Python with .py and .pyc
Verify that double-clicking on ApplyRE.py runs it. (It should also have a Python logo as its icon and be labeled «Python File», by the way.) If this isn’t already done, right-click on a .py file, choose Open With, Choose Program, and check «Always use…» This association improves convenience but isn’t strictly necessary—you can specify «python» every time you want to run a script, like this:
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:python32python 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 scriptsApplyRE.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 filessome lexicon.txt" "c:some filessome 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 scriptsApplyRE.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.