Windows powershell and python

Настройка локальной среды разработки для Python 3 в Windows 10

Python – это многофункциональный язык программирования для разработки различных программных проектов. Python вышел в свет в 1991 и назван в честь британской комик-группы Monty Python: так разработчики хотели подчеркнуть, что этот язык программирования настолько прост в использовании, что это даже смешно. Простота установки, относительно понятный синтаксис, немедленное сообщение об ошибках – благодаря таким своим качествам Python является отличным решением как для новичков, так и для опытных разработчиков. Python 3 – последняя версия языка – уже считается будущим Python.

Данное руководство поможет установить Python 3 на локальную машину Windows 10 и настроить среду разработки с помощью командной строки.

Требования

  • Локальная машина Windows 10.
  • Права администратора.
  • Подключение к сети Интернет.

1: Настройка PowerShell

Большая часть действий выполняется в интерфейсе командной строки, что представляет собой неграфической способ взаимодействия с компьютером: вместо нажатия кнопок вы взаимодействуете с машиной путём ввода текста. Командная строка (или оболочка) позволяет управлять задачами и автоматизировать большинство из них. Она является важным инструментом для разработчиков программного обеспечения.

PowerShell – это программа для Microsoft, которая предоставляет интерфейс командной строки. Административные задачи здесь выполняются с помощью так называемых командлетов (cmdlets) – специализированных классов .NET. Исходный код PowerShell стал открытым в августе 2016, благодаря чему программа PowerShell может использоваться на платформах Windows и UNIX (включая Mac и Linux).

Чтобы начать работу с PowerShell, кликните правой кнопкой на кнопку Пуск в левом нижнем углу экрана, выберите Поиск и введите в строку поиска PowerShell. В полученном результате выберите настольное приложение Windows PowerShell. Кликните правой кнопкой мыши и запустите его с правами администратора.

Программа запросит разрешение на внесение изменений, нажмите Да.

После этого на экране появится текстовый интерфейс:

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C: \Windows\system32> _

Перейдите в домашний каталог:

Теперь вы будете находиться в каталоге PS C:\Users\имя_пользователя (например, PS C:\Users\8host).

Чтобы настроить процесс установки, нужно изменить привилегии с помощью PowerShell. Существует несколько политик исполнения:

  • Restricted: политика исполнения по умолчанию. В таком режиме нельзя запускать сценарии. PowerShell будет работать только как интерактивная оболочка.
  • AllSigned: эта политика позволяет запускать сценарии и конфигурационные файлы, подписанные издателем, которому можно доверять. В таком режиме вы рискуете запустить вредоносный сценарий, у которого есть подпись такого издателя.
  • RemoteSigned: можно запускать сценарии и конфигурационные файлы, загруженные из интернета и подписанные издателем, которому доверяет ваша машина. Опять же, есть риск запустить подписанный сценарий, который на самом деле является вредоносным.
  • Unrestricted: можно запускать сценарии и конфигурационные файлы, загруженные из интернета, при условии, что вы подтвердите, что знаете о происхождении файла. В данном режиме цифровая подпись надёжного издателя не требуется. Конечно, в данном режиме очень высок риск запустить вредоносную программу или сценарий.

В данном руководстве используется политика исполнения RemoteSigned, которая позволит текущему пользователю принимать загруженные сценарии с цифровой подписью. Введите в PowerShell:

Set-ExecutionPolicy -Scope CurrentUser

PowerShell предложит выбрать политику исполнения. Введите:

Нажмите enter и подтвердите изменение политики. Чтобы убедиться, что политика изменилась и теперь у пользователя есть нужный уровень привилегий, запустите команду:

Она должна вернуть примерно такой вывод:

Scope ExecutionPolicy
—— —————
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine Undefined

Теперь текущий пользователь может запускать загруженные сценарии с цифровой подписью издателя, которому можно доверять.

2: Установка Chocolatey

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

Chocolatey – это пакетный менеджер командной строки для Windows, похожий на apt-get в Linux. Существует версия Chocolatey с открытым исходным кодом. Этот менеджер поможет быстро установить приложение или инструмент.

Прежде чем установить сценарий, ознакомьтесь с его содержимым и убедитесь, что он не причинит вреда системе. Используйте среду для выполнения сценариев .NET, чтобы загрузить и открыть сценарий Chocolatey в терминале. Создайте объект $script (вы можете выбрать любое имя для объекта, необходимо только сохранить символ $ в начале), который будет совместно использовать параметры интернет соединений с Internet Explorer.

Читайте также:  Maibenben установка windows 10

$script = New-Object Net.WebClient

Просмотрите доступные опции, объединив этот объект и класс Get-Member в один поток, который вернет все компоненты (свойства и методы) объекта WebClient:

$script | Get-Member
. . .
DownloadFileAsync Method void DownloadFileAsync(uri address, string fileName), void DownloadFileAsync(ur.
DownloadFileTaskAsync Method System.Threading.Tasks.Task DownloadFileTaskAsync(string address, string fileNa.
DownloadString Method string DownloadString(string address), string DownloadString(uri address)
DownloadStringAsync Method void DownloadStringAsync(uri address), void DownloadStringAsync(uri address, Sy.
DownloadStringTaskAsync Method System.Threading.Tasks.Task[string] DownloadStringTaskAsync(string address), Sy…
. . .

В выводе можно найти метод DownloadString, с помощью которого вы сможете просмотреть содержимое и подпись сценария в окне PowerShell. Примените этот метод:

Изучите сценарий, а затем установите Chocolatey:

iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

Командлет iwr (или Invoke-WebRequest) позволяет извлекать данные из сети Интернет. Приведённая выше команда передаст сценарию этот командлет, который выполнит его содержимое и запустит установочный сценарий пакетного менеджера Chocolatey.

После установки Chocolatey вы можете установить дополнительные инструменты с помощью команды choco.

Примечание: Чтобы обновить Chocolatey, используйте:

choco upgrade chocolatey

С помощью пакетного менеджера можно установить все компоненты, необходимые для создания локальной среды разработки Python 3.

3: Установка текстового редактора nano (опционально)

Теперь нужно установить nano, текстовый редактор, который использует интерфейс командной строки. С его помощью можно писать программы прямо в PowerShell. Это не обязательно, вы можете использовать текстовый редактор с графическим интерфейсом (например, Notepad), но nano удобнее использовать с PowerShell.

Установите nano с помощью Chocolatey.

choco install -y nano

Флаг –y автоматически подтверждает все действия.

После установки nano у вас появится доступ к команде nano, с помощью которой можно создавать новые текстовые файлы и писать программы Python.

4: Установка Python 3

Установите Python 3 с помощью Chocolatey:

choco install -y python

PowerShell установит Python 3 и сгенерирует вывод.

После завершения установки убедитесь, что Python установлен. Запросите версию Python:

Команда должна вернуть:

Вместе с Python будет установлен pip, пакетный менеджер Python. На всякий случай обновите его:

python -m pip install —upgrade pip

Chocolatey может вызывать Python 3 с помощью команды python. Флаг –m запускает модуль библиотеки как сценарий.

После установки Python и обновления pip можно приступать к настройке виртуальной среды для разработки проектов.

5: Настройка виртуальной среды

Теперь все компоненты (Chocolatey, nano, Python) установлены, и вы можете создать среду разработки с помощью модуля venv.

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

Среда разработки позволяет управлять проектами Python и обработкой различных версий пакетов, что особенно важно при работе со сторонними пакетами.

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

Выберите или создайте каталог для среды разработки Python.

mkdir Environments
cd Environments

Чтобы создать в этом каталоге виртуальную среду, введите:

python -m venv my_env

Примечание: Вместо my_env введите имя среды.

Эта команда создаст новый каталог (в данном случае my_env), содержащий такие компоненты:

ls my_env
Mode LastWriteTime Length Name
—- ————- —— —-
d—— 8/22/2016 2:20 PM Include
d—— 8/22/2016 2:20 PM Lib
d—— 8/22/2016 2:20 PM Scripts
-a—- 8/22/2016 2:20 PM 107 pyvenv.cfg

Эти файлы изолируют проект от общей системы локальной машины, благодаря чему системные файлы и файлы проекта не смешиваются и никак не влияют друг на друга. Это обеспечивает удобное управление версиями, а также доступ проектов к зависимостям и необходимым версиям пакетов.

Теперь нужно включить виртуальную среду:

Эта команда запустит сценарий activate из каталога Scripts. Теперь командная строка будет выглядеть так:

(my_env) PS C: \Users\8host\Environments>

Это позволяет вам определить, в какой именно среде вы находитесь. Все команды, запущенные в такой среде, будут действовать только в рамках этой среды.

6: Создание простой программы

Теперь проверьте работу виртуальной среды. Для этого попробуйте создать простую программу, которая будет отвечать «Hello, World!».

Откройте nano и создайте файл:

(my_env) PS C:\Users\8host> nano hello.py

Чтобы закрыть nano, нажмите Ctrl + X, чтобы сохранить изменения – Y и Enter.

После этого запустите программу:

(my_env) PS C:\Users\8host> python hello.py

Программа hello.py должна ответить:

Чтобы закрыть среду, просто введите:

Эта команда вернёт вас в исходный каталог.

Заключение

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

Adam the Automator

PowerShell vs. Python: A Battle for the Ages

Mohamed Mostafa

Read more posts by this author.

What’s the best programming language? You might get ten different answers when asking ten different developers. In this article, we’re going to compare two languages; PowerShell and Python. You will get a glimpse into each of these languages and understand how they compare and contrast in features such as syntax, availability across platforms, and more.

Читайте также:  Windows 2012 wsus console

It’s time for a PowerShell vs. Python bout!

By the end of this article, you’ll be able to answer some common questions:

  • What do both of these languages have in common?
  • What makes them different?
  • What are the best use cases for each of them?
  • How does the syntax differ?
  • What kind of role would someone have to best leverage one over the other?

This article is for those who have little to no knowledge about either language and are confused about whether to use PowerShell or Python. This article is also for those who already understand one of the languages, and would like to learn about the other.

Table of Contents

By Job Role

Although you might be able to talk about the technical aspects of Python and PowerShell all day, an important part of comparing the two languages is to determine what kind of job role most suits either language.

Both PowerShell and Python were developed on two sides of a fence (Microsoft and the open source Linux community). Both languages’ syntax, community, and therefore, their overall feel are different and thus are generally adopted to certain job roles

It should be noted here, that PowerShell (Core), which in version 6.0.0 and later, has been open-sourced. Times are a changin’.

System Administrators

Both PowerShell and Python are great languages to learn for sysadmins. They are both great automation tools, and can potentially lots of time for a sysadmin. Arguably though, for Windows sysadmins, PowerShell will be a better choice just because of its native .NET framework integration.

Python, on the other hand, is great for Linux sysadmins.

Although Python and PowerShell (Core) are both cross-platform, you’ll find that the large majority of job roles out there will be split between Windows and PowerShell, and Python and Linux.

Developers

For more developer-oriented jobs, Python is by far the leader. Python has massive support in areas that PowerShell has never touched, such as data science, statistical analysis, and more. Python feels more like a scientifically-oriented language sometimes.

Python also runs many large server-side web apps and other “developer friendly” applications.

Although PowerShell can be used as a development language, it’s typically better suited in job roles that need more automation, like DevOps or general sysadmin automation.

By Operating System

PowerShell

PowerShell is the hero for Windows environments; it’s the best skill you can leverage for automating tasks in Windows. This is especially true when it comes to products like Active Directory and Microsoft Exchange in both on-premises and Office 365 varieties.

Since PowerShell has direct access to the .NET Framework, it’s perfectly integrated with all Windows systems and can easily be used to accomplish any task.

However, PowerShell does have Linux support but, as of this writing, it’s not nearly as prevalent as Python.

Python

Python is generally better in Linux environments. Due to its deep roots in the Linux community, you’ll find Python modules to do nearly anything in Linux.

Python can also run on other platforms such as iOS and AIX.

By Task

PowerShell

You can use PowerShell to create a tool for administering daily tasks, and you can even create a GUI using Windows PowerShell for your tool to be more user-friendly.

Python

Python is generally best used for “heavier” tasks like machine learning, statistics, data science, and server-side web and desktop applications. Python also has great support for image processing.

Understanding the Syntax Commonalities and Differences

Let’s get down to the nuts and bolts of each language to compare and contrast them.

PowerShell and Python are object-oriented, which means both are built on the concept of logical objects where they create, manipulate, and reuse objects to perform specific tasks.

Both PowerShell and Python reuse code by the means of modules. Modules can be potentially reused later in other programs, or you can directly import modules created by other programmers.

Both languages have a large library of modules which you can easily use in your scripts.

PowerShell is task-based command-line shell and scripting language built on top of .NET framework which accepts and returns .NET framework objects, whereas Python is an interpreted programming language

Читайте также:  Графическая оболочка windows что такое утилиты

The Python interpreter takes the human-readable code and creates another form of code which is understood by the interpreter, to be changed later to a machine-readable code where the actual execution happens.

Let’s now start with the basics of both languages, such as commenting, declaring variables, conditions, and other basics, to get a better sense of their similarities and differences.

Commenting

Making a single line comment in PowerShell or Python is identical – use the hash sign ( # ) at the beginning of the line like below.

Declaring Variables

All variables in PowerShell start with a $ followed by a name. Below you can see how a variable is assigned to hold an integer.

Defining string variables works the same way in PowerShell, but you’ll need to enclose the value in single or double quotes.

Check out the about_Variables document for more information about PowerShell variables.

In Python, variables are treated nearly identical but do not require the variable to start with an $ .

You can learn more about Python variables via W3Schools other many other online resources.

Working with Math Operations

In PowerShell and Python, any positive or negative number without decimals is an integer. By default, they will be automatically assigned to a variable of type integer. Math operations can be executed normally on these variables.

In PowerShell, you can see some examples of some basic math operations below.

Similarly, in Python, you can do basic math operations as well shown below.

Learn more about math operations in Python in this helpful geeks2geeks.com article.

Making use of Conditional Statements

Conditional statements are important to any programming language. Conditional statements allow the developer to redirect the flow of the code, depending on one or more conditions. When you get into conditional statements like if/then constructs, you’ll find that PowerShell and Python are nearly identical.

You can see below that there is a slight, but very important, difference between the two languages. PowerShell is heavily dependent on parentheses ( ), curly braces < >, and other special characters, but Python uses indentation.

Notice all of the parentheses and curly braces below in the PowerShell example.

Contradict PowerShell code with the Python code below. You will only see colons to indicate the end of conditional statements and spaces to indicate the code to execute inside.

To demonstrate, let’s see how a typical PowerShell if/then statement looks and behaves. When the below code is run, you will see an output of 77 is greater than 70 .

In contrast, notice how the same task is performed in Python. There are quite a few differences including different operators and commands to output text to the console.

Looping

Another important concept in programming languages is looping. Loops allow a language to repeat, or iterate over, a piece of code continually until a condition is met, or for a certain number of times.

In PowerShell, a common foreach statement would look like below.

In Python, a similar loop performing the same task would use a for loop as shown below.

There is a great deal of similarity in the syntax used by PowerShell and Python, especially for the basics and core use of the languages. These similarities are a huge advantage for the anyone who masters PowerShell and wants to learn more about Python, or vice versa.

Solving the Same Problem Differently

Let’s now show how to solve a common problem a little differently with both PowerShell and Python. To do that, we’re going to read a simple text file with line-delimited numbers and only return a certain range of numbers to the console.

The file we’ll be using is called input_text.txt and line-delimited numbers contains a wide range of numbers from 1 to 6345.

We’ll create a function in both PowerShell and Python to process all of the numbers returned from the file.

Processing a File with PowerShell

Below you will see how you could make this happen in PowerShell.

When you run Get-TwoDigits , you will see that PowerShell will only return any number in input_text.txt that is between 9 and 99.

Processing a File with Python

Now, we’ll perform the exact same steps with Python to notice the syntax differences.

When you run the two_digits() function, you will see that Python will only return any number in input_text.txt that is between 9 and 99.

Creating a function in Python is almost the same structure. Keep in mind that indentation is vital in Python, as is case sensitivity.

Оцените статью