Python

How To Run A Python Script?

How To Run A Python Script

Are you a beginner in Python programming? The very first thing that you need to learn is to run a Python script. It will enable you to understand whether the code will work or not. Hence, you can efficiently handle the issues. There are different ways of running a Python script, but what are they? In this post we will tell you all you need to know on how to run a Python script. Let’s dive in.

How To Run A Python Script? The Python logo

Table des matières

How to run a Python script – what is Python, its basics, and how to get started with Python?

Python is the most popular programming language on the planet. It comes with a significantly easy syntax. As a result, anyone can quickly get familiar with it. Also, Python is widely used in web development, data science, and machine learning (ML) and AI projects. Hence, there is no shortage of jobs for talented developers.

You can consider Python as both a scripting and programming language. It can work both as a compiler and an interactive interpreter. A standard Python compiler can compile the lines of textual program code into binary bytecodes. Then the Python runtime can interpret the bytecode, just like Java and C runtimes do.

However, there is a historical relationship between general-purpose programming languages and scripting languages. Therefore, it will be more appropriate to consider Python as a general-purpose programming language rather than a specific purpose like Logo or TCL.

To get started with Python, you need to understand the syntax. Also, you have to learn all the basic concepts, including classes, functions, object-oriented programming, etc. Besides, you will need a tool to run a python script.

How To Run A Python Script? A close-up of a Python script

Scripts vs. Modules: What’s the difference?

In computing, a script is a simple program stored in a plain text file. It contains a logical sequence of orders or a batch-processing file. It enables you to sequentially execute the command.

A module is also a plain text file. However, it contains Python code. You can import the code or use it from another Python file.

Therefore, there is a subtle difference between a module and a script. Scripts are designed to be executed. On the other hand, modules are designed to be imported.

How to run a python script – what do you need to run a Python script?

To run a Python script, you need to ensure the following things:

  • Check if you have already installed Python on your PC. Simply run this code in the command prompt:

    If it’s not installed, go to the Python website to get the latest version of Python.

  • Download and install a high-performance code editor or IDE, like PyScripter.
  • Make sure to add Python to your system variable path. It will enable you to call it from the command line.

Read: 5 Real-Life Lessons About The Best IDE For Python

How to run a Python script – what’s the Python interpreter?

The Python interpreter is an application for running Python scripts. It works on the Read-Eval-Print-Loop (REPL) environment. Hence, it can read and evaluate the commands. Also, it can print the result, loop back, and repeat the process.

How To Run A Python Script? A keyboard

How to run a Python script – how to interactively run Python code?

You can run Python code through an interactive session. To start it, open the command line. Then you can write the code and hit enter to run it.

Let’s take an example of interactively running Python code on Windows. Simply open the terminal. Then add these lines:

The last line shows these characters: >>>. That means you have entered into the interactive mode.

Now, you can write and run Python code the way you like. For example:

How to run a Python script – how does the interpreter run Python scripts?

The interpreter runs Python scripts by following the Python Execution Model. Here are the steps:

  1. First, the interpreter sequentially processes the statements of your script.
  2. Then it compiles the source code to bytecode
  3. Finally, it ships off the code for execution.

In the last step, Python Virtual Machine (PVM) comes into play. The PVM is the runtime engine of Python. It sequentially runs your bytecode.

How to run a Python script – how do I execute Python code from the command line?

By using the Python interactive session, you can write and run a lot of code. However, you lose everything as soon as you close the session. That’s why you should write Python programs in plain text files with the .py extension. You can easily create the files in a plain text editor, like Notepad.

Let’s create a test script. Open your favorite text editor. Then create a new file. Next, write the following code:

Now, save the file with the name hello.py. You can run this Python script in different ways. Let’s find them out.

Using the “python” command

It is very easy to run Python scripts with the Python command. Simply follow these steps:

1. Open the command line. and type this line:

2. Hit the enter button. You will see this output:

That’s it! You have managed to run your very first Python script.

Redirecting the Output

Redirecting the output is another great way. It allows you to save the script output for later analysis. You can do it by using this command:

The command will redirect the output of hello.py to the output.txt file. The whole process is known as stream redirection. You can utilize it in both Windows and Unix-like systems.

Running modules with the -m option

The -m option allows you to run Python modules. It searches sys.path for the module name. It runs its content as main. Here is an example:

Using the script filename

Also, you can run the Python scripts by simply entering the file name. Here is an example to do it on Windows:

How to run a Python script – how to interactively run a Python script?

There are various ways for interactively running a Python script. Let’s find them out.

How to run a Python script – using “import”

Import in Python is analogous to #include in C or C++. You can import a module to load its content. Hence, you can conveniently access and use it later. By using import, the Python code in one module gets access to the code in another module.

Here is an example:

How to run a Python script – using importlib

importlib is a module. It provides the implementation of the import statement in Python source code. importlib contains the import_module. It can execute any module or script by imitating the import operation.

Here is an example:

Now, let’s take a look at another example that utilizes the importlib.reload() function. It is useful for modifying and testing changes without exiting the current session.

Here, you are re-importing the module. Because you cannot use import to run it for the second time. You can try using import after the first time. But it won’t do anything.

Keep in mind that you can only use a module object as the argument of reload(). But you can’t use a string. It will lead you to a TypeError.

Let’s try using a string as the argument of reload().

You will see this TypeError:

How to run a Python script – using runpy.run_module() and runpy.run_path()

runpy is a module of the Python Standard Library. It is used to locate and run Python modules without importing them first.

run_module() is a function in runpy. It can execute modules without importing them. Here is an example:

Keep in mind that the first argument of the run_module() must contain a string.

Similarly, runpy contains another function, called run_path(). It enables you to run a module by providing a location.

Let’s take a look at an example:

Here, you are specifying a file path by using runpy.run_path() function.

Both the runpy.run_module() and runpy.run() functions return the global dictionary of the executed module.

How to run a Python script – run Python script using exec()

You can utilize the built-in function exec() to run Python scripts. It is used for dynamic Python code execution.

Let’s take a look at an example:

Here, you are opening a Python file and reading its script.

How to run a Python script – run Python script using py_compile

The py_compile is a module. It provides a function to generate a byte-code file from a source file. It behaves like the import statement.

Let’s take a look at an example:

Here, you are using py_compile. compile() method to generate a byte code from first_script.py file.

The py_compile generates a new subdirectory, named “__pycache__”. Inside the subdirectory, the first_script.cpython-37.pyc file will be created. When you open it, you will see the output of the Python script.

How to run your Python script with an IDE or a text editor?

An integrated development environment (IDE) is software for building applications. It combines common developer tools into a single GUI. Hence, you can conveniently create applications.

There are plenty of IDEs available. For example, you can use Python IDLE. It is the default IDE of the standard Python Distribution. You can use it to write, debug, modify, and run your modules and scripts. Also, you can consider using other IDEs like PyCharm and Eclipse.

However, the best option is PyScripter. It is a feature-rich IDE. Also, it’s open-source. Hence, you don’t have to spend any money to use the IDE.

To run a Python script from your IDE or text editor, you need to create a project. Then you need to add your .py file to it. Also, you can simply create a new file with the IDE. Once you are done, run the file. If everything is OK, you will see the appropriate output.

Read: What Is The Best Python Editor In 2022?

Can I use browser-based IDEs to run a Python script?

Python is the most popular programming language on the planet. But unlike other languages, like JavaScript, it can’t be run in the browser.

How do I use a file manager to run Python scripts?

It’s very easy to run a Python script using File Manager. Simply double-click on its icon. It will start to run. The method might not be used in the development stage. But once you release the code, you are very likely to run it by double-clicking on the icon.

However, you need to meet some conditions to use the method. They depend on your operating system.

For instance, in Windows operating system, the .py and .pyw extensions are associated with the python.exe and pythonw.exe programs. Hence, you can double-click on them to run the scripts.

How to run your Python script using the built-in Python idle?

The way of executing a file in IDLE is very simple. Simply press the F5 key on your keyboard. The Python script will start to run. Alternatively, you can go to the menu bar and select Run > Run Module.

How to run a Python script as a module in another Python file?

There are multiple ways to make one Python file run another. Let’s find them out.

How to run a Python script – use a Python script like a module

How about importing the file you want to run? You can run its functions in another Python file. For instance, you need to import file1.py into file2.py. You have put all the files in the same folder. Inside file1.py, you have to add this line:

Now, you can call any function inside file2.py. For instance, you can call my_function() in this way:

How to run a Python script – use the “exec” command

You can use the exec command to run the Python script as a module in another file.

Here is an example:

Here, you are executing the file.py file in the interpreter.

How to run a Python script – use the “os.system” command

You can utilize the os.system command to spawn a new process.

Here is an example:

Why is Pyscripter one of the best ways to run a Python script?

PyScripter is free and open source. Hence, you don’t have to spend any penny to use it. Also, PyScripter lets you choose your preferred Python version. You just need to utilize command-line parameters. Besides, it provides full support for encoded Python source. Hence, PyScripter is considered to be one of the best tools to run a Python script.

PyScripter is a powerful Python IDE built on Delphi. It offers several amazing features, including the remote engine, remote debugger, and integrated unit testing. Try it now for free. 

FAQ

How do I run a Python script or code?

Simply open the command line. Next, type in the word python. Then insert the path to your script, just like this: python hello.py. Finally, press the Enter key. Your Python script will begin to run.

How do I run a .PY file in CMD?

Open Command Prompt. Then type “python” and your file name, like this: python hi.py. Once you are done, hit the Enter key. If everything is OK, your Python will start to run in CMD.

How do you run a .PY file on Windows?

On the latest version of Windows, you can run Python scripts by typing the Python file name in the command prompt. For example, you can run the hello.py file by entering this line: C:ehsanul> hello.py.

How do I run a Python script line by line?

You can run a Python code line by line by utilizing the Python interpreter. You can start it by installing the Python language on your PC. Then you have to launch the Command Prompt and type python.

How do I run Python in the terminal?

To run Python in the terminal, open the command line and type in python. Next, hit the Enter key. Python will begin to run in the terminal.

close
Related posts
Python

Embrace The Power Of Brand New Python 3.11 Features

Python

How To Exit A Python Script

CodeLearn PythonPythonWindows

How To Add Python Testing Tools Into Pandas Machine Learning Code

Python

Python Profilers: Learn The Basics Of A Profiler For Python

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée.

fr_FRFrench