Execute a Python Script

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

Python scripts can be executed by passing the script name to the python command or created as executable commands that can run stand-alone. You’ll learn how to create both in this lesson.

Let's create a script that we're going to execute with Python. We can do something as simple as say print("hello world!"). We can execute that by just typing Python and then passing in the name of the script and execute.

If we wanted to use Python 3, we need to call print as a function, save that, and then we can call it with the Python 3 command and again pass in the script name and it executes as well.

We can also make this a stand-alone executable. We'll include our shebang here and then pass in userbin env and tell it to find the Python environment. We need to mark that as executable, so we'll modify the attributes to include the executable bit. Now, we can type [inaudible 0:48] hello.py and it runs as well there.

Raunaq Sahni
Raunaq Sahni
~ 5 years ago

Hello Will,

I'm a little confused.

In order to make a file executable, is it recommended to add path to the python installed in the system or the python installed in the virtual environment? And also to which version 2 or 3?

Look forward to your response.

Will Button
Will Buttoninstructor
~ 5 years ago

Hi Raunaq, The path to the python executable should already be in your path. That is taken care of by the package manager when installing python. The version (2 or 3) is a tricky question. For example, I’m OSX the default version should be 2.7 but in Ubuntu it should be 3. This is why virtual environments are useful: if the application you are creating uses python3, create a virtual environment to support that and it will only apply to that venv, preventing it from affecting other python installations on your system. Hope that helps!

Sent from my iPhone

Markdown supported.
Become a member to join the discussionEnroll Today