Linux bash run python

Run Python Scripts in Linux Command Line

This quick tip shows how to run Python programs from the Linux command line.

If you want to do something, it is pretty much guaranteed that there is a Python script for it. So, when you have a Python script, how do you run it?

The simplest way is to use the python or python3 command in the following manner:

Some distributions have used python2 as python and have an explicit command python3 for python3. So if you want Python 3 to be guaranteed, use python3 .

Method 1: Run it using python

The easiest method to run a Python script on any Linux distribution is by invoking the python command and provide it with the name of your Python script.

This will ensure that if the file’s contents are valid, it will be executed without any problems.

Method 2: Make Python script executable

You may have encountered executing bash scripts simply by typing out their relative/absolute path in the terminal. i.e. you never had to do a bash .sh like you do with Python scripts by typing python .py

In order to achieve this, a few things should be done first.

If you might have noticed, the bash scripts that you can execute by simply typing out their relative/absolute path, they are «executable» files.

To make your Python script executable, run the following command in your terminal:

This should be it. Right? I have a file hello.py , let’s try running it.

$ cat hello.py print("Hello Linux Handbook!") $ chmod +x hello.py $ ./hello.py ./hello.py: 1: Syntax error: word unexpected (expecting ")")

Uh oh. What? Syntax error? But it is a valid Python program/script.

The reason why we got this error is because by making hello.py an executable file, all we did was tell the shell that «You can execute it», but not what interpreter/program to use when it is being executed.

My shell (bash) thought that it was a bash script. And hence, we got this error.

The solution to overcome this is pretty simple. Add the following line to the first line of your Python script.

The #! syntax is used mostly in scripts (where you need an interpreter). Now, the /usr/bin/env part means that we are calling env to find the python command from $PATH and execute it for us.

Читайте также:  Чем открыть файл dwg linux

This essentially starts Python for us, instead of the user needing to invoke it manually every time. And, if you don’t automate these things, are you even scripting?

Another reason to use env in shebang is to make it portable. Some systems have the Python executable interpreter stored as /usr/local/bin/python , while some might have /usr/bin/python .

Now, let’s try executing hello.py once again, but with the necessary changes made to it.

$ sed -i '1 i\#!/usr/bin/env python\n' hello.py $ cat hello.py #!/usr/bin/env python print("Hello Linux Handbook!") $ ./hello.py Hello Linux Handbook!

Oh hey! It runs flawlessly now.

Now that you know how to run Python programs from the terminal, how about learning to use Linux commands from Python scripts?

Источник

run python script directly from command line

I put that at the top of a script. I’ve seen that should make the script runnable from the command line without the need for python programname.py . Unless I’m misunderstanding I should be able to use programname.py as long as I have the above line at the top of the script. Is this correct? It isn’t working for me I just get an error indicating that I would have to use python at the beginning of the ‘call’.

3 Answers 3

Universal running of Python scripts

You can pretty much universally run without the shebang ( #! ) with

Or nearly equivalently (it places the current directory on your path and executes the module named myscript ) (preferably do this!):

from the command line, as long as you have Python installed and on your path environment variable (i.e. set to run with python , which, if installed, would typically be the case).

Shebangs ( #! ) are a Unix thing.

The shebang, as you’re using it, is typically for running on a Unix platform (typically Apple or Linux). Windows would typically require cygwin to use the shebang.

You can usually default to whatever python is available on your system path with:

Assuming you’re on a Unix, you might try other locations for your python setup, like:

Muddling through

You can see what python you’re currently using by using the unix which command, so if you want to see where your python is coming from, use this command:

or on Windows (cygwin probably can run the shebang):

On Linux/Unix, you’ll need execution perms to run the file as well, in that manner. Use chmod

(chmod also may apply to Cygwin in Windows)

If you’re not running as root, you may require sudo , and that would be

And then attempt to run (within the same directory) with

Источник

How to execute Python inline from a bash shell

Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file? Something similar to:

Читайте также:  Linux kernel based virtual machine kvm

4 Answers 4

From the manual, man python :

 -c command Specify the command to execute (see next section). This termi- nates the option list (following options are passed as arguments to the command). 

Also useful to remember that you can use ; to separate statements, e.g., python -c ‘import foo; foo.bar()’

Doesn’t work for me on python 3.8. Traceback (most recent call last): File ««, line 1, in NameError: name ‘Hi’ is not defined

Another way is to you use bash redirection:

And this works also with perl, ruby, and what not.

To save quote ‘ and » for python code, we can build the block with EOF

A ‘heredoc’ can be used to directly feed a script into the python interpreter:

Another way is to use the e module

Useless unless you’ve already run pip install e . For a standard python install, this produces the error: No module named e .

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to Run Python Scripts in Linux

Python is one of the most popular programming languages of all. It’s an interpreted, object-oriented, high-level programming language that features dynamic semantics. If you’re using Linux, then you’ll come across Python scripts quite frequently.

One of the most basic and crucial things to learn is running a Python script when learning or working with Python. Because Python is an interpreted language, it requires the Python interpreter to execute any Python code. Depending on the type of script, there are a couple of ways you can execute it.

This guide will showcase executing a sample Python script.

Python scripts

Any script is a text file containing the code. The file can then be run using an interpreter. The same goes for any Python script.

Generally, a Python script will have the file extension PY. However, there’s another way of writing a Python script: embedding Python codes into a bash script.

Either way, you need to have the Python package installed in your system. Because it’s a popular programming language, all Linux distros offer pre-built Python binaries directly from the official package servers. Distros like Ubuntu, Linux Mint, Pop! OS etc., comes with Python pre-installed. The package name should be “python” or “python3″ for any other distros”.

Working with a Python script

Creating a sample Python script

For demonstration, let’s make a quick Python script. Open up the terminal and create a file named sample-script.py.

To be able to run the script, it must be marked as an executable file. Mark the file as an executable.

Читайте также:  Linux list archive files

Check the file permission to verify if it worked.

Writing a sample Python code

Now, we’re going to put some code in the script. Open up the file in any text editor. For demonstration, I’m going to be using the nano text editor.

We’ll place a simple program that prints “hello world” on the console screen.

Save the file and close the editor.

Running the Python script

Finally, we can run the script. Call the Python interpreter and pass the location of the file.

Bash-style Python script

So far, we’ve seen the default way of running a Python script. However, there’s an unconventional way of writing and running a Python script as a shell script.

Generally, a shell script contains a list of commands that are interpreted and executed by a shell (bash, zsh, fish shell, etc.). A typical shell script uses shebang to declare the desired interpreter for the script.

We can take this structure to our advantage. We’ll declare the Python interpreter as the desired interpreter for our code. The body of the script will contain the desired Python scripts. Any modern shell will execute the script with the Python interpreter.

The structure will look something like this.

Location of Python interpreter

The shebang requires the path of the interpreter. It will tell the shell where to look for the interpreter. Generally, a Python interpreter is available as the command “python” or “python3”. Python 2 is deprecated, so it’s not recommended to use it anymore (except in very specific situations).

To find the location of the Python interpreter, use the which command. It finds the location of the binary of a command.

Creating a shell script

Similar to how we created the Python script, let’s create an empty shell script.

Mark the script as an executable file.

Writing a sample shell script

Open the script file in a text editor.

First, introduce the shebang with the location of the interpreter.

We’ll write a simple Python program that prints “hello world” on the next line.

Save the file and close the editor.

Running the script

Run the script as you’d run a shell script.

Final thought

It needs to be passed on to the interpreter to run a Python code. Using this principle, we can use various types of scripts to run our Python code. This guide demonstrated running Python scripts directly (filename.py scripts) or indirectly (filename.sh).

In Linux, scripts are generally used to automate certain tasks. If the task needs to be repeated regularly, it can also be automated with the help of crontab. Learn more about using crontab to automate various tasks.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

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