Introduction to Part 1 of “PowerShell Scripting guide to Python”
Interested Powershell developers can learn Python and benefit from this blog series. Python which is one of the top programming languages in the world and needless to talk about its importance and role in the world of development and infrastructure. PowerShell Scripting guide to Python would be helpful for you if you know PowerShell already.
It is designed to make you familiar with new concepts, syntax, and semantics of python so that you can totally relate to the concepts of PowerShell already in your arsenal, and learn this language fast.
Going forward in this series, we will talk about similarities and some differences. Purpose of this series is not to prove which language is better, hence I’ll leave you to judge benefits and drawbacks of PowerShell and Python over one another.
Prerequisites:
- Install Powershell v5.1
- Install Python v3.6.1 – I’m using Anaconda that has Python and bunch of other useful Python packages that come pre-installed, and here is a link to the Anaconda user manual if you want to download that.
- Set Environment variable PATH to point to the folder that has Python executable (Python.exe)
- [Optional] I’m using Visual Studio Code as an editor for both PowerShell and Python
Overview:
In this part, we will cover following items –
- Version Info
- Case sensitivity and indentation
- Comments
- Single-line comments
- Multi-line comments
- Variables
- Console I/O
- Object Introspection – methods and properties
- Help System
- Module
- Importing
- installing
- Checking data types
- Data Typecasting
- Saving and running commands as a script
- Passing command-line arguments to a script
Book – PowerShell Guide to Python
-
Checking Version Information
The version is probably the first thing we learn to check in PowerShell, using the automatic variable $PSVersionTable
While in python the version automatically appears when you launch python shell or call the python executable with the switch –version
There would be scenarios where you want to check Python version dynamically during the code execution, for which you can import sys module and check the version_info attribute
-
Case Sensitivity and Indentation
Powershell is case-insensitive scripting language but Python is strictly case-sensitive, hence same keywords or names with a different case(s) are understood differently by the compiler.
Python is also strongly indented. Indents provide structure to the program and differentiate code blocks from one another.
In PowerShell Indentation is a matter of style, whereas in Python Indentation is a language requirement.
Following example demonstrates Python and Powershell codes with indentation,
and the below example shows how indentation is important in a Python program.
-
Comments
Single line comments Python is a Hash sign (#) followed by the comment, which is exactly what we are familiar in PowerShell, Whereas, Python multiline comments starts and ends with triple single or double quotes.
-
Variables
No need to specify Data types explicitly in the variable declaration in Powershell or Python, as both are Dynamically typed programming languages.
Following rules apply when naming Python variables
- The first character can be the underscore “_” or a capital or lower case letter.
- Following the first character can be anything which is permitted as a start character plus the digits.
- Since Python is case-sensitive so are the variable names!
- Python keywords are not allowed as variable names
-
Console Output
Python provides a print() function to print output to the console. Just like Write-Host cmdlet in PowerShell, in fact in PowerShell, it’s much simpler and we can directly output string to the console.
But, there is a catch, Write-Host sends output directly to the console.
Strings inside quotes are sent to a different PowerShell Stream called Output stream (the default PowerShell stream) , which can be piped and be used by cmdlets following the pipeline or can be stored in a variable.
-
Console Input
User input can be captured using the input() function in Python
and in PowerShell, we use Read-Host cmdlet to get user inputs
-
Object Introspection
In PowerShell to introspect members of an object we pass the object to Get-Member cmdlet
and in Python, you can use a built-in function dir() to list attributes and methods of an object
Get the members of an object using Python library ‘inspect‘ .
-
Help System
PowerShell provides a very robust help system through Get-Help cmdlet, where we can see examples and understand how PowerShell works.
Python Help system is accessed with the inbuilt method help().
-
Modules
- Importing ModulesPowerShell Import-module Cmdlet is to import modules in the current session, whereas Python Provides a keyword import
- Installing Modules
Installing modules in python using PIP Package manager which downloads and installs packages from an online repository
-
Checking data types
Powershell Objects provide an inbuilt function GetType() to check the data type
Similarly, in python, we can use the type() inbuilt method to test/check the data type
-
Type conversions
Sometimes it’s necessary to perform conversions between the built-in types. To convert between types you simply use the type name as a function in Python.
PowerShell provides type accelerators to typecast data types
-
Saving and running a script
PowerShell scripts have extension .ps1 and .py extension for the Python programs
In order run a script in python you can call thePython executable (python.exe) with filename\path like in the below image.
-
Passing command line arguments to a Python script
Argv attribute of sys module in Python provides the list of command-line arguments passed to the Python program.
It’s basically an array holding the command line arguments of our program.
Don’t forget that the counting starts at zero 0, not one 1 and by default the first argument, sys.argv[0], is always the name of the program where it was invoked.
Hope you enjoyed reading this article and let me know your feedback.
In the Part-2 of this blog series we would be covering String manipulations hence, please stay tuned!
Blog Series
Till now we’ve covered the following topics…
- Part 1 – Intro, Prerequisites, Case & indents, comments, variables, console I/O, object introspection, Help, Modules, dataTypes, typecasting, command line arguments
- Part 2 – Date, Time, TimeDelta, TimeSpan, Strings and String manipulations.
- Part 3 – Data Structure – Array, ArrayList, List, HashTables, Dictionary, Sets, Tuples
Prateek Singh
Related posts
16 Comments
Categories
Author of Books
Awards
Open Sourced Projects
Author at
Blog Roll
Mike F RobbinsDamien Van Robaeys
Stéphane van Gulick
Kevin Marquette
Adam Bertram
Stephanos Constantinou
Francois-Xavier Cat
Ravikanth Chaganti
Roman Levchenko
Blog Stats
- 1,133,055 People Reached
Awesome style bro. Looking forward for next post in this series.
Thanks, Manvendra, I’m glad you liked it! Looking forward to meeting expectations. 🙂
Good one to start with for Python.. 🙂
Thanks Prakash, stay tuned for next part of the series!
This is fantastic. Well done/thank you, Prateek.
You’re welcome!
[…] you are new please refer to the part-1 of this blog series for Python prerequisites, if you want to do hands-on with this blog […]
Hi, not sure where to ask a question regarding Powershell command executed via Python. It seems any shell, subprocessing,, Popen or os.system command invoke of a Powershell command produces a different output than if it was run natively bypassing Python. Do you know how to call Powershell and invoke commands via Python without having different results than calling from Terminal, command line?
Thanks for guide. Very useful. Small error though in 11. Type Conversions:
# bool to int
bool(1)
bool(0)
# int to bool
int(True)
int(False)
Should be opposite:
# bool to int
int(True)
int(False)
# int to bool
bool(1)
bool(0)
good sharing thank you
[…] you are new please refer to the part-1 of this blog series for Python prerequisites and to get an idea of what has been […]
[…] Lien utile : RIDICURIOUS […]
13. Passing command line arguments to a Python script…
I was expecting a #14. Passing command line arguments to a PowerShell script…
…since you were showing side-by-side comparisons with the other item numbers.
Disappointed, but enjoyed your Part 1 and will continue.
Perhaps you would back-track and include “#14 Passing command line arguments to a PowerShell script…”
If you have that explanation elsewhere, please let me know.
Thank you,
Tim (new subscriber)
What is the powershell equivalent to file redirect? Like in linux we have
> python script.py < input.txt
In powershell I get "The '<' operator is reserved for future use."
How can we redirect an input file to python in powershell?
like in linux: python script.py < input.txt
It doesnt seem to work in powershell
This was awsome. Thanks a lot Bro!!