How to Run Python Programs/Scripts

How to Run Python Programs/Scripts

Introduction

So you have finally creatd the perfect script or just downloaded a really cool program built in Python but aren’t quite sure how to run it? Well in this tutorial we are going to cover how to run Python scripts and programs on various different operating systems! Strap in, this is a fun one and much easier than you think!

Prerequisites

If you haven’t already, you need to make sure that you have installed Python to your system or that Python is already installed be default on your system. If you are unsure of how to do this, please check out one of our guides on how to do so: Install Python on Ubuntu or Install Python on Windows. MacOS and Linux usually already come with Python installed by default, and these articles will let you know how to check to see what version you are running and to make sure your terminal or command prompt has access to the Python command already.

Windows

Command Line

So the first one up today is how to run these scripts from the Windoes command line. This is going to be most similar to other operating systems like Linux and MacOS. To begin first open up a command prompt by searching in the Windows Search Bar, or by pressing Windows Key + R and typing in cmd.exe

Once you have the command prompt open, simply navigate to the folder that contains the script you are looking to run with the cd command.

cd (Change Directory) to your Python Files

cd path/to/your/files

Once you have gotten to the location that houses your files that end in .py, then to run those scripts, all you need to do is simple type out the following.

Run the Python Script/Program

python some_script_name_here.py
python path/to/script/some_script_name_here.py

Now of course the python prefix can vary, if you followed my tutorial on how to Install Python on Windows, then you will know all about the py launcher feature that lets you specify different versions of python easily like so:

How to Use PY Launcher to Run Multiple Versions of Python

py -2 some_script_name_here.py
py -3 some_script_name_here.py
py -3.10 some_script_name_here.py

So that is about it when it comes to running Python scripts in the Windows Command Line. This is basically the same process for Linux and MacOS, though I don’t believe those OS’s have the py luancher feature built in, but we will cover that in those sections.

NOTE: You do NOT have to navigate to the script directly to execute it, you can provide the path to the script from whatever directory you are in without needing to navigate there directly.

Windows GUI

To run Python scripts from the Windoes GUI using your mouse, it is as simple as double clicking on the script or program files that you wish to run. This will then open a popup window asking you how you would like to open this file. Select the Python option and the script or program should start running. You can choose Always or Just Once. If you choose Always, it will always use Python to open your .py files and you will never have to mess around with that again. If you choose Just Once, you will need to select this option each time. This is available on Windows 11. Older versions of Windows have a different way to handle this that I explain later on.

Run Python Script by Double Clicking

Be aware, that they may flash the command prompt briefly and vanish, this is because there is no pause or break before the end of the program execution to keep the window open. If this is a script that you have built yourself you may need to put in a break or pause at the end of the file in order to keep the window open if it is a console based application.

If this is launching a GUI like Tkinter or something else, then the program should just launch like normal Windows applications without issue.

Setting the Default Program for Older Versions of Windows

As I mentioned before, older versions of Windows don’t have the Just Once and Always options. You can also set the default program to handle opening all .py files on the system if you do not want to have to select Python each time. To do this, simply navigate to any Python file in your system:

right-click on that script-> choose open with-> choose default program-> more options-> and select the python.exe option.

Creating a Batch Script

Ok, so you want something a little more robust that can maybe run multiple scripts at once and that you can just double click on and it runs without having to deal with selecting Python each time to run the scipt or program. Well batch scripting is the best way to handle this in Windows and allows you to do some really powerful stuff! We will be creating an entire series on batch scripting in the future, but for now lets look at the basics of setting up a simple script to handle running your python scripts.

Creating a Batch Script to Run Python Files on Windows

@echo off

rem Run first Python script
echo Running first Python script...
python C:\path\to\first_script.py

rem Run second Python script
echo Running second Python script...
python C:\path\to\second_script.py

rem Run third Python script
echo Running third Python script...
python C:\path\to\third_script.py

rem End of script
echo All scripts have been run.
pause # Used to pause the Console/Terminal so you can see the output of the program

In this script, the @echo off command turns off the echoing of commands in the console window. Then, the first Python script is run using the python command and the path to the script file. This is repeated for the second and third scripts. Finally, the script outputs a message that all scripts have been run and pauses to wait for the user to press a key before closing the console window.

As you can see this is rather simple to do and is very powerful allowing you to run multiple Python scripts in a row. Just to clarify, the rem in this script is for remarks and allows you to add comments to the script. If you wish to see the code in the console, such as running a script or program that is a console app, make sure to exclude the @echo off line at the top of the script. Next lets cover how to do this in Linux!

Linux

Terminal

Ok so much of what we covered in the Windows section also applies to Linux and by extension to macOS, with slight differences. In Linux, you can open the python scripts or programs in the terminal app by also typing out

Run Python in the Linux Terminal

python path/to/file/some_script_name.py
python script_name.py

I have provided two different ways, which can also be done in Windows. One lets you set the full path to the file you wish to run from whatever directory you are currently in without having to navigate to it, and the other allows you to run a script in the directory you are currently in. You can do the same on Windows, and just like how I explained in the Windows section, you can cd to the location of your script directly instead.

Linux GUI

To double click and run a Python script or program from the Linux GUI you will need to make the script or program executable. To do this, you will need to go into the Terminal app and run a simple command against the file in question. Once you have done that, you will be able to double click and run the file.

Make Python Script Executable

chmod +x script_name.py

Next, you will want to make sure that the Python script or program that you are wanting to run has this shebang at the top of the file so the system knows what interpreter to run:

Add Shebang/Hashbang to Python Script

#!/usr/bin/env python3

At this point, you should be able to double click on the file in the GUI and have it run or just run it from the terminal app by specifying its name only.

Run Executable Python Script

script_name.py

Another additional step that you can take is to move the script or program file to a directory that is included in your system PATH, so that you can run the script from anywhere on the system without needing to type out the full path to the script or navigate to its directory directly.

Move Script to Directory in System Path

sudo mv script_name.py /usr/local/bin/

Special Note

Remember earlier I mentioned the py launcher that was available on Windows. This is a Windows specific tool to allow switching versions of Python easily. This tool is not available on Linux or MacOS so you will either need to type out the full path to the Python interpreter that you want to use, set up Symlinks, or use something like Python2 or Python3 in order to run the scripts. To setup a Symlink, it is rather straight forward:

How to Symbolic Link Python Versions to Different Commands

sudo ln -s /usr/bin/python3.9 /usr/local/bin/python3.9 # name of the command you will call
sudo ln -s /usr/bin/python2.7 /usr/local/bin/python2.7

# How to call the new symlinks
python3.9 script.py 
python2.7 script.py

So as you can see, the command is rather simple, but allows you to create any name that you wish to use to call various versions of Python in Linux and MacOS. The name you specify at the end of the /usr/local/bin/ is the name of the command that you will use to call that version of Python. Make sure the paths to the versions of Python you are symlinking are correct or you will not be able to run the scripts or programs that you wish.

Linux Shell/Bash Script

So just like on Windows, you can easily create shell/bash scripts to run multiple Python scripts or programs at once. The term Bash or Shell are often used interchangeably in Linux as they refer to the Bash shell. There are other shells available on Linux, but this is the most common one that you will encounter. To create the shell script, you just need to do a few simple steps:

Create a Shell/Bash Script File and Run It

You can use something like Nano, Vim, or Gedit in order to create the shell script file that will house the code to run your Python script or program.

Create and Open a New Shell Script

nano runscript.sh # Creates a new file and opens it in Nano
vim runscript.sh # Creates a new file and opens it in Vim
gedit runscript.sh # Creates a new file and opens it in Gedit

Code to Include in Shell Script

#!/bin/bash
python myscript.py # Only works if the Shell Script and Python Script are in the same directoy
python /path/to/script/myscript.py # Best to put the full path if you want to run the script from anywhere

Make the Shell Script Executable and Run It

chmod +x runscript.sh # Make the script executable
./runscript.sh # Run the script

So as you can see, it is very similar to the Windows batch script with just a couple extra steps in that you need to mark the script as executable and then run it. You should also be able to just double click the script now that it is executable from the GUI and have it run that way as well. Also be aware that this functionality is defined by the file manager that you are running. While most Linux file managers support double clicking and running shell scripts that have already been marked as executable, not all do. If you run into any issues, google your file manager that you are using to see if it supports this feature or not, and how to enable it if it is not enabled by default. I would cover how to do that here, but there are so many different ones, it would be impossible to list them all.

In the next section we will cover MacOS and wrap this tutorial up!

MacOS

Terminal

So very similar to Linux, you are just going to type out:

Running Python Script on MacOS Terminal

python script_name.py
python path/to/script/script_name.py

Nothing needs to change here as both Linux and MacOS are based off of Unix and share many of the same commands and ways to run things. 

MacOS GUI

So unlike Linux there may be some additional steps to allow double clicking and running a Python script on MacOS. 

The general idea is the same, you first need to chmod +x the script and then double click on it. MacOS however sometimes will prevent you from running unsigned programs. Lets recap making the script executable and then I will talk about how to get around gatekeeper on Mac to allow you to run the script or program.

Make Python Script executable on MacOS

chmod +x script_name.py
chmod +x path/to/script/script_name.py

Ok, so that covers marking the script as executable, now you can try double clicking on it and see if it will run. If not, Gatekeeper is preventing unsigned programs from running on your system and you need to bypass it.

WARNING: this is not something to do lightly and only do it on software and scripts that you trust. 

These are the steps you will need to take in order to grant permission for your script or program to run:

  1. Open System Preferences.
  2. Click on Security & Privacy.
  3. Click on the General tab.
  4. Under “Allow apps downloaded from,” select “App Store and identified developers” or “Anywhere” (if it’s available).

Note: “Anywhere” is not available by default on newer versions of macOS, but you can enable it by running the following command in the terminal:

Disable Gatekeeper on MacOS

sudo spctl --master-disable

This will disable Gatekeeper, which enforces code signing and verification of downloaded apps.

WARNING: Disabling Gatekeeper can increase the security risks on your system. Make sure you only run trusted software from trusted sources.

This warning is worth repeating as it can be dangerous if you run scripts or software you did not write yourself and open youself up to malware and other attacks.

MacOS Shell Script

Same as the Linux shell script you can also create these on MacOS to run mutliple Python files at once or just have an easy way to execute a script with some CLI parameters that you may not want to type out everytime. Ill show a quick example below but it is the same process as on Linux. 

Create MacOS Shell Script

vim myscript.sh

Add Code to Shell Script with CLI Parameters - MacOS

#!/bin/bash

python3 /path/to/your/python/script.py "$1" "$2"

Mark Shell Script Executable and Run It

chmod +x myscript.sh
./myscript.sh arg1 arg2

So this script can except some CLI parameters that can then passed into the python script or program each time it is ran. You can also double click the shell script and run it if you have permission or if you have disabled Gatekeeper to run unsigned code. 

That about covers the most popular ways to run python scripts or programs in MacOS, lets wrap this tutorial up below.

Conclusion

So that about wraps up the various ways that you can run Python scripts on various OS’s. As you can see, there are several ways to acheive the same results and whichever you choose is honestly down to personal preference. Windows py launcher is really a handy tool that makes working with Python an enjoyable experience, which was not always the case on Windows in years past. With the power of Symlinks on Linux and MacOS, that is honestly the easiest route to take. Of course you can create shell scripts as well, just like creating a batch script on Windows to handle running more than one Python script or program at a time.

We hope you enjoyed this tutorial and learned something new today. As always, feel free to look around at our ever expanding set of tutorials and leave us a comment and share with your friends if you found this content helpful!

Install Python on Ubuntu 22.10

Install Python on Ubuntu 22.10

Introduction

Hello everyone, today we are going to look at installing Python on Ubuntu 22.10, but this will also apply to any version of Ubuntu that uses the apt-get package management system. To get started, you are first going to need to open up your terminal. The shortcut for this is Ctrl + Alt + T. Once the terminal is open then you need to install the version of Python that you would like. 

By default, any newer version of Ubuntu is going to come pre-installed with Python 3. This will usually be one of the latest versions that are available at the time of the Ubuntu release, but it may be even newer if you have already updated your system packages to the lastest and greatest. 

Install default Python 2/3: 

To get started lets assume you are wanting to install an older version of Python like Python 2. 

Install Python Command

sudo apt-get install python2

Once you press enter, you will see a bunch of package names appear that need to be installed along with a prompt asking if you are sure you wish to install these packages. Type in ‘Y’ and hit enter again for the packages to be installed. Congratulations, you have installed python to your system!

Now if you accidentally deleted Python 3 or corrupted the install somehow, it is the same process to install it to your system, expect instead of python2 you will type python3 like so:

Install Python 3 Command

sudo apt-get install python3

Install any version of Python

As you can see installing python to linux, especially on Ubuntu is rather simple and fast. Of course you can also very easily specify the exact version that you would like to install as well, if you need it for a specific project you are working on. To do so, simply type out the following command:

Install any version of Python

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5

Lets break down what these commands are doing and how to use them. The first command is adding a new repository for your system to pull from. Think of a repository as if it were a box that holds all your favorite software inside that you can easily download at any time you wish. In fact you are already using repositories with the installation method of the most recent versions of python, and those just happened to be included by default when you install Ubuntu for you.

Next we are updating the system and packages to make sure everything is properly configured and seen.

Finally we are saying hey, grab this package names python3.5 for me and download it and install it.

Anytime in the future that you need a different version of python, you can now specify the exact version number that you need and you are able to get the version directly in your terminal without having to build python from source or from a wheel file or anything else like that. It really is the easiest solution.

Run Python in the Terminal

Now how do you use the versions of Python that you have installed on the system? Well that is quite simple with the following command:

How to open and use python in the terminal

python2
python3
python3.5

So each command would open a different version of python to use. Just use one command at a time depending on what version you want to launch inside of your terminal. python2 will open the interactive environment in the terminal for the latest version of Python 2 that you have installed. python3 will open the latest version of python3 that you have installed. If you have installed any of the python versions specifically like 3.5 then typing python3.5 will open that version for you.

Of course this is oversimplifying symlinking and how the system knows exactly what you open up, but you need not worry about that right now and just understand the system is able to keep track of your installs if you have installed them like I have indicated above.

Remove Installed Packages

If you ever need to remove a python install, or any package for that matter, it is generally as easy as:

Uninstall package

sudo apt autoremove package-name(python3, python2, etc.)

# example below to remove python2

sudo apt autoremove python2

When you type in this command it will tell you what will be uninstalled and ask you if you are sure. Type ‘Y’ if you want to remove the package from the system or ‘n’ if you do not want to.

Conclusion

So that about wraps up this tutoral. There is an accomanying video tutorial if that is more your speed and is less than 3 minutes long. Hope this tutorial helped to teach you a little about installing packages on Ubuntu and specifically how to install Python and its various versions. 

As always thank you all for your support and helping make this website the success that it is. While your hear, why not check out some of our other tutorials or share them with frends or coworkers? Until next time. 

Python 3.12 Alpha 6 Released

Python 3.12 Alpha 6 Released

Python 3.12.0 Alpha 6 Released: A Sneak Peek at the Upcoming Changes

Python, the popular high-level programming language, has released the sixth alpha version of Python 3.12, giving developers a preview of the upcoming changes. The new release is available for download from the official Python website.

What’s New in Python 3.12.0 Alpha 6?

As an early developer preview, Python 3.12 alpha 6 offers a glimpse of the changes and improvements in store for the language. Here are some of the major new features and changes that have been implemented so far:

  • Improved Error Messages: Python 3.12 provides even better error messages, with more exceptions suggesting solutions to users for typos.
  • Linux perf Profiler Support: The latest version includes support for the Linux perf profiler to report Python function names in traces.
  • Removal of Deprecated Features: Python 3.12 has removed several deprecated modules, methods, and classes, including wstr and wstr_length members, smtpd and distutils modules, and others.
  • String Backslash Escape Sequences: Invalid backslash escape sequences in strings now warn with SyntaxWarning instead of DeprecationWarning, making them more visible.
  • Internal Representation of Integers: Python 3.12 has changed the internal representation of integers to prepare for performance enhancements.

What’s Next for Python 3.12?

Python 3.12 is still in the development phase, with one more alpha release planned before the beta phase starts in May 2023. During the alpha phase, new features may still be added, and existing ones may be modified or removed, so developers should use caution before incorporating the new features into production environments.

For more details on the changes in Python 3.12, visit the “What’s New in Python 3.12” page on the Python website. If you think an important feature is missing from the list, you can inform the core developers. The next pre-release of Python 3.12, 3.12.0a7, is scheduled for release on April 3, 2023.

 

source: Python Blog

Why Python?

Why Python?

Introduction

Python is one of the most popular programming languages in the world, with a vibrant community of developers and a wide range of applications. It’s also an excellent language for beginners who are just starting to learn programming. In this blog post, we’ll take a closer look at what Python is and why it’s such a great language to start with.

What is Python?

Python is a high-level, interpreted programming language that was first released in 1991. It was created by Guido van Rossum, a Dutch programmer who was looking for a simple, easy-to-learn language that could be used for a variety of tasks. Since then, Python has become one of the most widely used programming languages in the world.

Python is known for its clean syntax and readability, which make it easy to write and understand code. It’s also a versatile language that can be used for a wide range of applications, including web development, data analysis, artificial intelligence, and more.

Why is Python a great starting language?

There are many reasons why Python is a great language for beginners. Here are just a few:

Simple and easy to learn

Python’s syntax is designed to be simple and easy to understand. This makes it a great language for beginners who are just starting to learn programming. Unlike other languages, Python doesn’t require you to memorize complex syntax rules or understand intricate programming concepts before you can start writing code.

For example, let’s take a look at a simple “Hello, world!” program written in Python:

Python Hello World

print('Hello, World!')
   Whatever you do, just be active and As you can see, the code is straightforward and easy to read. This is just one of the many reasons why Python is a great starting language.

Large community and support

Python has a large and vibrant community of developers who are constantly creating new libraries, tools, and frameworks. This means that if you run into a problem while learning Python, you’re likely to find a solution online. There are also many tutorials, guides, and forums available to help you learn the language.

Versatile

Python is a versatile language that can be used for a wide range of applications. Whether you’re interested in web development, data analysis, artificial intelligence, or something else, Python has a library or framework that can help you get started.

For example, if you’re interested in web development, you can use the Flask or Django frameworks to build web applications. If you’re interested in data analysis, you can use the Pandas library to manipulate data and the Matplotlib library to create visualizations.

Career opportunities

Learning Python can open up many career opportunities, as it’s one of the most widely used programming languages in the world. According to the TIOBE Index, Python is currently the third most popular programming language, after Java and C.

Python is used by many companies, including Google, Facebook, Amazon, and Microsoft. It’s also used in a wide range of industries, including finance, healthcare, and education.

Getting started with Python

If you’re interested in learning Python, there are many resources available to help you get started. Here are a few steps you can take:

Install Python

The first step to learning Python is to install it on your computer. Check out our step by step guide on how to install Python today! Install Python. Once you’ve installed Python, you can use a text editor or an integrated development environment (IDE) to write and run your code.

Learn the basics

Once you’ve installed Python, you can start learning the basics of the language. There are many online tutorials and courses available, such as Codecademy’s Python course, that can help you get started as well as our very own site Learn Code Today! Whatever you chose, be sure to stick to it, take it slow, and don’t get discouraged. You are going to be learning a lot, and it may feel overwhelming, but we have all been there at one point or another!

Practice, practice, practice

The key to learning any programming language is to practice writing code. You can start by writing simple programs, such as a program that prints out the numbers from 1 to 10 or a program that asks the user for their name and greets them.

As you become more comfortable with the language, you can move on to more complex programs, such as web applications or data analysis scripts.

Join a community

As mentioned earlier, Python has a large and vibrant community of developers. Joining a community can be a great way to get support and learn from others who are also learning the language. You can join online forums, such as Reddit’s r/learnpython or Stack Overflow, or attend local Python meetups. Whatever you do, just be active and you will pick up the language in no time.

Build projects

One of the best ways to learn Python is to build projects. Projects can help you apply what you’ve learned and give you a sense of accomplishment. You can build projects in a wide range of areas, such as web development, data analysis, game development, and more.

Here are a few project ideas to get you started:

  • Build a web application using the Flask or Django framework. Maybe create an application that tracks what movies you own, or what ingredients you have at home for cooking.
  • Analyze data using the Pandas library and create visualizations using the Matplotlib library. There are loads of free data dumps on the web to practice with, a simple google search should yield some fun results!
  • Build a game using the Pygame library. Pygame is a great starting point to see your code visually and have fun at the same time! Start off with something simple like a 2d platformer.
  • Build a chatbot using the NLTK library. If you are reading this and have access to the ChatGPT API, look at making your own desktop version that runs natively out of the web browser!

Conclusion

Python is a great starting language for beginners who are interested in learning programming. It’s simple, easy to learn, versatile, and has a large community of developers. Learning Python can open up many career opportunities, as it’s widely used in many industries.

If you’re interested in learning Python, there are many resources available to help you get started. Install Python, learn the basics, practice writing code, join a community, and build projects. With time and practice, you can become proficient in Python and use it to build amazing things.

AI jobs and Python

AI jobs and Python

The Future of Jobs and Artificial Intelligence

Artificial intelligence (AI) and machine learning (ML) have been buzzwords in the technology industry for a while now, with many fearing that AI will replace human jobs. However, the truth is that AI and ML are more likely to complement human creativity than supplant it. In this blog post, we’ll discuss the current state of AI and ML, industries that are embracing it, and what it means for job seekers.

Industries Embracing AI

According to the newest 2022 AI Index Report from Stanford’s Institute for Human-Centered Artificial Intelligence, virtually every industry has increased its investments in AI-savvy people. However, some industries are more aggressively embracing AI than others. Information, professional, scientific, and technical services, and finance and insurance are among the industries with the highest AI-centric job postings.

Python: The Key to Future Job Success

If you’re worried about your job or simply want to capitalize on the trend of AI and ML, there’s one word you need to know: Python. Python has become the lingua franca for experts and novices alike as they dive into data science. In the Stanford report, Python stands out both for its relative growth compared to other desired skills and its absolute growth. Python helps reduce the complexity inherent in AI/ML by providing a bevy of powerful libraries that simplify development.

The Impact of AI on Jobs

According to a different study conducted by researchers at the University of Pennsylvania and funded by OpenAI, “around 80% of the U.S. workforce could have at least 10% of their work tasks affected by the introduction of LLMs, while approximately 19% of workers may see at least 50% of their tasks impacted.” This means that some industries, such as accountants, mathematicians, interpreters, and creative writers, are more at risk of being impacted by AI and ML than others.

The Good News about AI and Jobs

While AI and ML are likely to impact jobs, this news needn’t be bad. As we’re seeing with software development, AI can remove some of the tedium of a given job while freeing up employees to focus on higher-value tasks. For those looking to bolster their chances in this AI-driven future, learning Python and other AI-related skills can be key to success.

Conclusion

In conclusion, AI and ML are here to stay, and they will continue to shape the job market. While some jobs may be impacted, there are opportunities for individuals to capitalize on the trend by learning Python and other AI-related skills. As businesses continue to embrace AI, it will become increasingly important for job seekers to stay up-to-date on the latest technologies and skillsets.

Pin It on Pinterest