Как установить python через консоль windows

To install Python on Windows using the command prompt, download the installer and run it with the appropriate options to ensure Python is added to your PATH.

start /wait python-installer.exe /quiet InstallAllUsers=1 PrependPath=1

Why Use Command Prompt to Install Python?

Using Command Prompt to install Python has several advantages over the traditional graphical user interface (GUI) installation method. Here are the key reasons why you might choose to use cmd:

  • Speed: The command line allows you to skip multiple windows and dialogs. You can execute commands quickly and reliably.
  • Automation: Installing Python via cmd enables automation through scripting, allowing you to replicate setups or streamline installations across multiple systems.
  • Troubleshooting: Errors and issues are usually more apparent in cmd, making it easier to identify and resolve problems.

Set Path Cmd Windows: A Quick Guide to Path Management

Set Path Cmd Windows: A Quick Guide to Path Management

Prerequisites for Installing Python

Before diving into the installation process, it’s crucial to ensure your system is ready.

Check for Existing Python Installations

First, you need to verify if Python is already installed on your system, as having it can lead to conflicts or unnecessary reinstalls. To check, run the following command in Command Prompt:

python --version

If Python is installed, this command will display the installed version. If nothing appears or an error appears indicating that the command is not recognized, you will need to proceed with the installation.

Verify Command Prompt Access

Make sure you can access Command Prompt (cmd). It’s a straightforward application included with Windows, and you can access it by searching for «cmd» in the Start menu.

How to Install Python on Windows 11 Using Cmd

How to Install Python on Windows 11 Using Cmd

Downloading Python

Finding the Right Version

When downloading Python, it’s essential to choose the latest stable version that supports your applications. The official Python website is your best resource for this.

Using Command Prompt to Download Python

You can download Python directly through cmd, negating the need to use your browser. If you have `curl` or PowerShell available, you can execute the following command:

curl -O https://www.python.org/ftp/python/x.x.x/python-x.x.x-amd64.exe

Replace `x.x.x` with the desired version number. This command will download the Python installer directly to your current directory.

List Files Cmd Windows: A Simple Guide

List Files Cmd Windows: A Simple Guide

Installing Python Using Command Prompt

Navigating to the Downloads Folder

Once you have downloaded the installer, you’ll need to navigate to the folder where it was saved. The Downloads folder is the default location for most browser downloads. Use the following command:

cd %USERPROFILE%\Downloads

This command changes the directory to your Downloads folder, where the Python installer should be located.

Running the Installer

Now, it’s time to run the installer from cmd. Below is the command to execute the downloaded installer:

python-x.x.x-amd64.exe /quiet InstallAllUsers=1 PrependPath=1

Breakdown of Command Flags

  • `/quiet`: This flag ensures that the installation runs silently, without interruptions.
  • `InstallAllUsers=1`: This flag installs Python for all users on the system, not just the current user.
  • `PrependPath=1`: This automatically adds Python to the system PATH, allowing you to run Python commands from any directory.

List Disk Cmd Windows: Quick Guide to Disks Management

List Disk Cmd Windows: Quick Guide to Disks Management

Verifying the Installation

Checking the Python Version

To verify that Python was successfully installed, you can run the following command:

python --version

If the installation was successful, this command will show the version of Python you installed. If you encounter an error stating that the command is not recognized, you may need to troubleshoot the installation process or check your system PATH settings.

Install Windows From Cmd: A Quick How-To Guide

Install Windows From Cmd: A Quick How-To Guide

Setting Up Your Environment

Installing pip: Python’s Package Installer

pip is the package installer for Python and is essential for managing additional Python libraries. To verify if pip was installed along with Python, run the following command:

pip --version

This command will confirm whether pip is available. If it’s not installed, you may need to reinstall Python and ensure that pip is included in the installation settings.

Creating a Virtual Environment

Creating a virtual environment is highly recommended for managing dependencies for different projects. Here’s how to create and activate a virtual environment using cmd:

  1. Create the virtual environment:
python -m venv myenv
  1. Activate the virtual environment:
myenv\Scripts\activate

Activating the virtual environment allows you to install packages in an isolated space which helps prevent conflicts between project dependencies.

Install Windows 10 Cmd: Quick and Easy Guide

Install Windows 10 Cmd: Quick and Easy Guide

Common Issues and Troubleshooting

Installation Errors

While installing Python via cmd, you may encounter various issues. Common errors include insufficient permissions or problems with the installation flags. If you run into problems, check if you’re running Command Prompt as an administrator.

Python Not Recognized

If you receive an error stating that Python is not recognized after installation, it is often due to the PATH variable not being set correctly. You may need to manually add the Python installation path to your system’s environment variables.

Install Windows Service Cmd: A Quick How-To Guide

Install Windows Service Cmd: A Quick How-To Guide

Conclusion

Installing Python using Command Prompt on Windows is not only efficient but opens the door to greater control over your Python programming environment. With the steps provided, you should be able to successfully install Python and manage your projects seamlessly using cmd. As you practice and become more comfortable with these commands, you can unlock the full potential of your Python development experience.

Mastering Diskpart Cmd Windows 10: Your Quick Guide

Mastering Diskpart Cmd Windows 10: Your Quick Guide

Additional Resources

For more information, visit the official Python documentation at [python.org](https://docs.python.org). Additionally, various online tutorials can enhance your cmd skills and Python knowledge.

Mastering Python Cmd Input for Effective Command Line Use

Mastering Python Cmd Input for Effective Command Line Use

Call-to-Action

If you found this guide helpful, consider subscribing to our service for more quick and concise cmd tutorials. Share your experiences or any questions you may have in the comments section below!

Необходимо передать Python-проект вместе с библиотеками человеку, у которого нет интерпретатора. Решил все сделать через батник, но полазив в гугле так и не нашел команду для установки python.
Что нужно прописать в консоли windows, чтобы установить python + pip и необходимые библиотеки?


  • Вопрос задан

  • 14736 просмотров


Комментировать


Подписаться

1



Оценить


Комментировать


Решения вопроса 2

res2001

@res2001

Developer, ex-admin

Запустите установщик питона с ключом /? и узнайте, что в стандартном инсталяторе есть возможность тихой установки, а так же там есть ссылка на страничку с документацией по установке питона, в которой в деталях все расписано.


Комментировать

Пригласить эксперта


Ваш ответ на вопрос

Войдите, чтобы написать ответ


Похожие вопросы


  • Показать ещё
    Загружается…

Минуточку внимания

Реклама

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Введение

Python — один из самых популярных языков программирования в мире, и его скрипты часто запускаются через командную строку. В этой статье мы подробно рассмотрим, как установить Python, проверить его установку и запустить скрипт через командную строку. Эти шаги помогут вам начать работать с Python и использовать его для автоматизации задач, написания скриптов и многого другого. Мы также обсудим некоторые полезные советы и инструменты, которые могут облегчить вашу работу с Python.

Кинга Идем в IT: пошаговый план для смены профессии

Установка Python

Прежде чем запустить Python скрипт, необходимо установить сам Python. Процесс установки может немного отличаться в зависимости от операционной системы, которую вы используете. Давайте рассмотрим, как это сделать на разных платформах.

Windows

  1. Перейдите на официальный сайт Python: python.org.
  2. Скачайте последнюю версию Python для Windows. Обычно это будет установочный файл с расширением .exe.
  3. Запустите установочный файл и следуйте инструкциям на экране. Обязательно отметьте опцию «Add Python to PATH» перед началом установки. Это добавит Python в системные переменные PATH, что позволит запускать Python из любой директории через командную строку.

macOS

  1. Откройте терминал. Вы можете найти его в папке «Программы» -> «Утилиты» или воспользоваться поиском Spotlight.
  2. Введите команду brew install python3. Homebrew — это популярный менеджер пакетов для macOS, который упрощает установку различных программ.
  3. Если у вас не установлен Homebrew, сначала установите его, следуя инструкциям на официальном сайте Homebrew. Установка Homebrew также потребует установки Xcode Command Line Tools, если они еще не установлены.

Linux

  1. Откройте терминал. В зависимости от вашего дистрибутива, это может быть GNOME Terminal, Konsole или другой терминал.
  2. Введите команду для установки Python. Для дистрибутивов на базе Debian (например, Ubuntu) используйте:

    Для дистрибутивов на базе Red Hat (например, Fedora) используйте:

  3. Убедитесь, что вы используете команду с правами суперпользователя (sudo), так как установка программ требует административных прав.

Проверка установки Python

После установки Python важно убедиться, что он установлен правильно и доступен через командную строку. Это поможет избежать проблем при запуске скриптов в будущем.

Windows

  1. Откройте командную строку. Для этого нажмите Win + R, введите cmd и нажмите Enter.
  2. Введите команду python --version или python3 --version.

Если установка прошла успешно, вы увидите версию Python, например, Python 3.9.1. Если команда не распознается, возможно, Python не был добавлен в PATH. В этом случае вам нужно будет добавить его вручную через настройки системы.

macOS и Linux

  1. Откройте терминал.
  2. Введите команду python3 --version.

Вы должны увидеть версию Python, например, Python 3.9.1. Если команда не распознается, убедитесь, что Python установлен правильно и доступен в PATH.

Запуск Python скрипта через командную строку

Теперь, когда Python установлен и проверен, можно запустить Python скрипт через командную строку. Давайте рассмотрим этот процесс более подробно.

Создание простого скрипта

Для начала создадим простой скрипт. Откройте текстовый редактор, такой как Notepad (Windows), TextEdit (macOS) или gedit (Linux), и введите следующий код:

Сохраните файл с расширением .py, например, hello.py. Убедитесь, что файл сохранен в директории, к которой у вас есть доступ через командную строку или терминал.

Запуск скрипта

Windows

  1. Откройте командную строку.
  2. Перейдите в директорию, где сохранен ваш скрипт, используя команду cd. Например, если скрипт находится на рабочем столе, введите:

  3. Введите команду для запуска скрипта:

Если все сделано правильно, вы увидите вывод Hello, World! в командной строке.

macOS и Linux

  1. Откройте терминал.
  2. Перейдите в директорию, где сохранен ваш скрипт, используя команду cd. Например, если скрипт находится в папке «Documents», введите:

  3. Введите команду для запуска скрипта:

Если все сделано правильно, вы увидите вывод Hello, World! в терминале.

Заключение и полезные советы

Запуск Python скриптов через командную строку — это базовый, но важный навык для любого программиста. Вот несколько полезных советов, которые помогут вам работать с Python более эффективно:

  • 📝 Редактирование пути: Если вы часто работаете с Python, добавьте путь к Python в системные переменные PATH, чтобы не вводить полный путь к интерпретатору каждый раз. Это можно сделать через настройки системы (Windows) или файл .bash_profile (macOS и Linux).
  • 🐍 Использование виртуальных окружений: Для управления зависимостями и изоляции проектов используйте виртуальные окружения. Создайте виртуальное окружение с помощью команды python -m venv myenv и активируйте его перед запуском скриптов. Это поможет избежать конфликтов между различными версиями библиотек.
  • 🔄 Автоматизация задач: Используйте Python скрипты для автоматизации рутинных задач, таких как обработка файлов, работа с API и многое другое. Например, вы можете написать скрипт для автоматического резервного копирования важных файлов или для отправки уведомлений по электронной почте.
  • 📚 Изучение документации: Официальная документация Python — это отличный ресурс для изучения языка и его возможностей. Посетите docs.python.org для получения подробной информации о стандартной библиотеке и различных модулях.
  • 🛠 Использование IDE: Интегрированные среды разработки (IDE) могут значительно упростить процесс написания и отладки кода. Попробуйте использовать такие инструменты, как PyCharm, VS Code или Jupyter Notebook для работы с Python.

Теперь вы знаете, как установить Python, проверить его установку и запустить скрипт через командную строку. Эти знания помогут вам начать работу с Python и использовать его для решения различных задач. Удачи в ваших начинаниях с Python!

Читайте также

Installing Python 3 on Windows 11 or 10 machines is not difficult, however, if you are a beginner then we have discussed the both Graphical and command prompt ways to install it. Especially, for those who are not much familiar with Python, it is an open-source high-level interpreted programming language.

Installing Python 3 on Windows 10 or 111. Download Python’s latest version2. Start Python Installation on Windows3. Check version4. Stop Python from opening the Microsoft store5. Open PowerShell, CMD, or Terminal (Admin)6. List Python versions7. Use Winget to install Python8. Run a simple program

It is known for its versatility because it has been used widely for programming applications, web development, data analysis, machine learning, artificial intelligence, data visualization, web scraping, and scientific computing. The reason behind’s Python popularity among the developer community is its clear syntax, readability, ease of use, and large number of libraries & frameworks. All this is possible because of a vast but active community.

Python also supports most of the popular IDEs or can be written using a simple text file created using Notepad.

Let’s go through the article, whether you are a beginner or experienced, in this tutorial we will find the necessary steps required to install and set up Python on Windows operating systems.

Installing Python 3 on Windows 10 or 11

Here we are discussing two ways to set up Python one is using the graphical installation wizard and the other with the help of a command in prompt or Powershell (Terminal).

Using GUI:

1. Download Python’s latest version

As we know Python is not included in Windows by default to compile our programs based on it. Therefore, visit the official website- python.org to download the latest version by clicking on the Download button.

Download Python for windows

2. Start Python Installation on Windows

After following the previous steps, you would already have the executable file of python on your Windows.

  • Double-click python executable to start the installation wizard.
  • Select the “Add Python.exe to PATH” box otherwise, we won’t be able to run PIP or Python using native Windows Powershell or command prompt.
  • After that click on the Install Now option.
Add python.exe to path

  • The setup will start running, this will also install PIP and documentation on your system.
Installing PIP pacakge manager

  • Finish the installation by clicking on the Close button.
Python installaion is done

3. Check version

To confirm, the installation is successful without any error, let’s check the version of installed Python and PIP. For this, you can either use the Command prompt or Powershell. Alternatively, we can also run the Python terminal app to issue commands, for that in your Windows Search type – python as its app appears, and click to open it.  You will have a Python interpreter with version details as well.

 python --version

To check the PIP version

pip -V

Note: If typing python on on command terminal or Powershell, opens the Microsoft Store then go through the next step.

Check  version

4. Stop Python from opening the Microsoft store

By default, if you type python on the command prompt or PowerShell in Windows, it will open Microsoft Store to download another version of Python instead of using the existing version of your Python. To stop that and tell the system to run the one you have installed, Follow the steps:

  1. Go to the Windows Search box
  2. Type- Manage App Execution Aliases
  3. As its icon appears click to open it.
  4. Search for Python3 and Python App Installers
  5. Turn off the toggle button given there for them.
  6. Close your CMD Terminal or Powershell and reopen it again.
  7. Now,  type python in that to check your current version.
Stop Python from opening the Microsoft store

#Use the command line method

5. Open PowerShell, CMD, or Terminal (Admin)

Right-click on the Windows Start button and select Terminal (Admin). If you have PowerShell then you can go for that as well.

6. List Python versions

When you go for command line installation there are multiple versions available to install. We can use Winget to first check what are those and, later, to install them as well.

winget search Python.Python
winget command to search python

7. Use Winget to install Python

Once you have decided which version is suitable for your project then set it up using the following syntax.

winget install Python.Python.version-number

For example, if you want to have 3.11 then the command will be like this:

winget install Python.Python.3.11

When you are done with it, close your CMD terminal or PowerShell and reopen it again to check, whether it is working or not.

For that either use:

pip -V

or 

 python --version

8. Run a simple program

Open the Python command line and type:

print ('Hey I am here with Python')

The above code will print “Hey I am here with Python” on your screen.

Run a simple program

Other Articles:

  • How to install and use Python on Windows 7
  • 8 Best ways to start Command Prompt in Windows 10
  • Best 5 Books to Learn Python Programming?
  • How to make Python 3 your default “Python Version” on Windows

python-on-windows

A step-by-step guide on installing Python and using the Command Prompt for Windows

  • Version: 1.1.0
  • Date: 2017-01-03
  • Author: Alberto Pettarin (contact)
  • License: Creative Commons Attribution 4.0 International (CC BY 4.0)

Overview

Do you want to run a Python program under Windows,
but you have no experience using the Command Prompt?

This guide is for you!

I will walk you through the installation of Python
and I will explain the basics of the Command Prompt.

After reading this page (and practicing a bit),
you should be able to run a Python program
confidently and safely.

What Is Python?

Python is a
high-level, general-purpose programming language
which allows people to easily create and share programs
for a variety of applications.

The Python project is a free (libre)/open source software (FLOSS) initiative,
managed by the Python Software Foundation.
You can download, install, and use Python for free
on several platforms,
including Linux, Mac OS X, and Windows computers.

Python enables the development of FLOSS programs,
which are created for free
by millions of volunteers around the globe
and shared in source code form.
This means that the end user
who receives or downloads a Python program
can actually check that the program does what
is supposed to do, and nothing more
(unlike closed-source programs,
which send personal information to third parties,
show you advertisements, or
damage your computer).

More details on Python can be found on the
official Python page
and on its
Wikipedia page.

In practice, to use a Python program you need two pieces of software:

  • the Python interpreter, which is the «master» program
    that reads the source code of a Python program,
    and «execute» it; and
  • the source code of the Python program,
    usually consisting of one or more files with .py extension,
    which performs the specific task you are interested in.

This guide explains how to install the former,
and it shows how to run the latter
in the Command Prompt of Windows,
with a complete, real-life example.

Installing Python On Windows

The preliminary step consists in installing
the Python interpreter (i.e., the «master program»)
on your computer.

Installing Python is a one-time operation.
If you already installed Python in the past
(for example, to run a different program),
you do not need to install it again,
and you can skip to the next section.

Step 0: Should I Get Python 2 Or Python 3?

At the time of writing (2017-01-01),
there are two main versions of Python:
Python 2 (2.7.13) and Python 3 (3.6.0).

Discussing the technical differences between these two versions
is beyond the scope of this guide.
It suffices to say that
some Python programs work with both versions of Python,
while other Python programs work only
with Python 2 but not with Python 3,
or vice versa.

You should get the version of Python that the program
you are interested in recommends.

If the latter does not specify a version,
get the latest Python 3 version available.
If you later discover that your Python program
does not work with the Python version you installed,
do not worry: just uninstall it, and install the other one!

In the rest of the guide we assume you need Python 3.

Step 1: Download The Installer

First, open your Web browser and
go to https://python.org/:

Python home page

Click on the Download > Latest Python 3.6.0 link.

You will get a page listing all the new features of Python 3.6.0:

Python 3.6.0 download page

Scroll down until you see the list of available downloads:

Python 3.6.0 downloads

If you have a recent Windows computer,
very likely it is a 64-bit machine,
so you should download the file labeled Windows x86-64 executable installer,
and save it on your Download folder or on your Desktop:

Python 3.6.0 downloads

Downloading the file will take from few seconds to a few minutes,
depending on the bandwidth of your Internet connection.

(If you have an older PC that you know is a 32-bit computer,
download the Windows x86 executable installer instead.
You can tell whether your PC is a 32-bit or a 64-bit machine
by reading the System Information in the Windows Control Panel.)

Step 2: Install Python

Double-click on the file you just downloaded
to start the installation wizard:

Python 3.6.0 installer

By default, the Add Python 3.6 to PATH option is disabled,
but you should select it,
as it makes running Python programs much much easier.

Most users should click the Install Now button,
which installs Python with the default settings.
(If you want to personalize your installation
or you are told to enable some advanced features,
click on the Customize installation option instead.)

The installer might ask you for administrative privileges
or for confirmations like the following:

Python 3.6.0 installer asking for confirmation

You can safely answer Yes.

A progress bar will appear:

Python 3.6.0 installer progress bar

until the installation completes with the following message:

Python 3.6.0 installer completed

Starting with Python 3.6.0,
it is recommended to click on
the Disable path length limit option,
before closing the installer.
If you do so, you will get a final confirmation dialog:

Python 3.6.0 installer completed

You can terminate the installation by clicking the Close button.

Congratulations, you have your first Python installation under your belt!

Using The Command Prompt

Most Python programs are command line interface (CLI) utilities,
which means that they are not operated
via a graphical user interface (GUI),
also known as «the program window».
Instead, they must be executed
in the Command Prompt of Windows,
also known as «shell» or «terminal».

Running a CLI program means
typing a command string on the Command Prompt of Windows,
following a certain syntax
which depends on what the program is supposed to do.
You can think of this act as reciting the «right spell»
to get your job done.

Opening A Command Prompt

To open the Command Prompt,
locate the Command Prompt icon in your Start menu
(or use the search bar):

Command Prompt icon

Click on the icon. A black window appears:

Command Prompt window

The first two lines printed in the window
show the version of the Command Prompt.
The last line, which reads C:\Users\IEUser> in the screenshot above,
is the prompt, where you can actually type commands.

The prompt line always starts
with the location of the working directory,
that is, the folder where the command prompt is currently acting upon
(C:\Users\IEUser in the screenshot above),
and ends with the > character.

The prompt normally opens in the home directory of the current user:
in fact, we are in C:\Users\IEUser,
because the user is called IEUser.
If your Windows username is Olga,
it is likely you will see
C:\Users\Olga instead.

(Different versions of Windows might have different paths for home directories.)

In the documentation of Python programs you might find a $ character
before examples of commands, as follows:

$ python my_awesome_program.py

because on Linux and Mac OS X machines
the terminal prompt is usually a $ character.

You should not type the $ character,
it is just a placeholder for your actual prompt.
For any practical purpose,
you can mentally replace the $ with your actual prompt,
like C:\Users\IEUser> in the example above,
as if the documentation was as follows:

C:\Users\IEUser> python my_awesome_program.py

(You will actually type only python my_awesome_program.py and
hit the Enter/Return key.)

The Three Safety Rules

By issuing commands on the Command Prompt,
you can accidentally delete your own files or damage Windows,
so you must be careful.

Do not be afraid or discouraged:
you do not stop using knives just because
you can cut your fingers with them!

By following Three Safety Rules,
you can operate the prompt safely:

  1. Never issue a command without understanding what it does,
    and only run programs obtained from developers that you trust.
  2. If anything happens in the prompt that you do not understand,
    you can simply click on the «X» on the right top corner
    to close the Command Prompt window
    (and hopefully nothing bad will happen to your files).
  3. Always copy your Python program in a separate
    folder, and always make copies of your input files in it,
    so that you can just throw away the Python program folder
    if something goes wrong, and start over.

Changing The Working Directory (cd)

As said above, the command prompt normally opens
in the home directory of your user:

Command Prompt window

If you want to change the current working directory,
you can use the cd command.
For example, to move to the C:\ directory
(the root directory of your C: drive),
you type cd C:\
and press the Enter/Return key:

Command Prompt window

Notice that the prompt changed to C:\>.

Listing The Contents Of The Working Directory (dir)

If you want a list of the files or subdirectories
contained in the current working directory,
issue the dir command, without arguments:

Command Prompt window

The prompt shows a list of directories and files
that are contained in the C: drive:
in the above screenshot they are
BGinfo, PerfLogs, …, Windows.

At this point, if you want to enter the Users directory,
you can simply type cd Users, and so on.

If you want to go up one level, type cd ..
(two full stop character).
For example, if you are in C:\Users\ and give a cd ..,
you will end up in C:\.

If you want to clear the prompt window, use the cls command.

Checking That Python Is Installed Correctly

If you selected the Add Python to PATH option,
you can run the Python interpreter (and any Python program)
from any current working directory.

To check this, give the python --version command:

Python non-interactive execution

The Python version will be printed
(e.g., Python 3.6.0)
and you will get back to the Windows prompt.
You just ran Python in non-interactive mode,
meaning that you provided a precise command
(«Python, print the version number you are»),
the Python interpreter performed what you asked for,
and then it returned control to the Command Prompt of Windows.

The non-interactive mode is how most Python programs work.

If you forget to add the --version parameter
after the python command,
you will enter the interactive Python shell instead:

Entering Python interactive shell

Notice how the prompt changed to >>>.

To exit the Python shell, and return to the Command Prompt,
just type quit() and hit the Enter/Return key:

Leaving Python interactive shell

Discussing the interactive shell is beyond the scope of this guide,
since most programs you are interested in are non-interactive.

Running A Python Program

Excellent, now you have all the tools required
to run a Python program on the command line.

As an illustration,
I will use my simple Python script
export-kobo,
which reads annotations and highlights
from the database file of a Kobo eReader device (KoboReader.sqlite),
and prints them on the prompt or exports them to an output file.

Step 1: Download The Source Code

First, download the source code of the Python program you want to run.

This usually implies downloading either a single Python source code file
(with extension .py), or a ZIP file containing several Python source code files
and other resource files that you need to uncompress somewhere on your disk.

The exact details depend on your Python program,
hence be sure to carefully read its install documentation.
You can download the prescribed files with your browser,
and then copy/uncompress them using the Windows graphical file manager.

In our example, we download the raw file
export-kobo.py
from the GitHub repository.

Remember Safety Rule 3
(«copy your Python files into a separate folder»)?

We put the downloaded export-kobo.py file
in a new folder C:\export-kobo:

Running a Python program

Note that we also copied
the KoboReader.sqlite file
(the input of our Python program)
from our Kobo eReader
to the same folder.

Step 2: Open A Command Prompt And cd There

Then, open a Command Prompt as explained above,
and change the current working directory to the folder
where you put your Python program source files.

In our example, cd C:\export-kobo:

Running a Python program

A simpler alternative to using the cd command
takes advantages of the Windows file explorer.
Just navigate the file explorer to the folder
where your Python code is:

Opening a prompt from file explorer

and select the
File > Open command prompt > Open command prompt
menu:

Opening a prompt from file explorer

you will get a new Command Prompt window,
already located at the correct directory:

Opening a prompt from file explorer

Step 3: Run The Python Program

At this point, we are ready to run our program.

Type python export-kobo.py KoboReader.sqlite --list and hit Enter/Return:

Running a Python program

The Python interpreter will load our export-kobo.py program,
and run it with arguments KoboReader.sqlite and --list.

Clearly, the semantics of the arguments vary from program to program,
depending on what each program is supposed to do.

In our case, export-kobo.py will read the file
whose name is passed as the first parameter (KoboReader.sqlite)
and it will list (--list option) the titles of all the eBooks
with annotations or highlights in the database.

If we specify different command arguments, for example
python export-kobo.py KoboReader.sqlite --csv --output exported.csv,
we will get a different behavior:

Running a Python program

In particular, this second command exported all the information
contained in the KoboReader.sqlite file into
the newly created file named exported.csv in CSV format:

Running a Python program

You must check the documentation of your Python program
to know the semantics of its arguments.

Usually, if you run a Python program without arguments
you will get a synopsis of the accepted arguments:

Running without arguments shows the synopsis

If a -h or --help argument is given,
then a more verbose help message will be printed:

Running with -h shows an help message

Congratulations, now you should be able
to download and run a Python program on your own!

Acknowledgments

  • Louise Schofield nee Stokes for suggesting using the file explorer menu
    to open the command prompt at a given directory

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Openssl for windows x64 portable
  • Windows server 2016 rdp не пускает больше 2 пользователей
  • Комфорт для глаз windows 10
  • Как запретить доступ к сайту на компьютере windows 10
  • Для чего нужен hyper v в windows 10