Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a Python script from Ubuntu Dash?

Tags:

python

ubuntu

I've written hello.py (a basic "hello world" program) and would like to be able to quickly run it on my Ubuntu machine by pressing the Win key to open Dash, then type the name of the script (or something similar to that).

However, when I type hello.py into Dash, it opens the file in an editor rather than execute it. I added a shebang line #!/usr/bin/env python3 and run chmod u+x hello.py, it still opens the file in an editor.

I tried creating a hello.sh shell script that will run the Python script, but the shell script also gets opened in the editor when I type its name into Dash.

Also, I tried pressing Alt-F2 and it brings up something like Windows' Win-R, but when I enter python3 hello.py it doesn't bring up a terminal window to display any print() output.

Is there a way to run a Python script by typing its name into Dash? Or is there another easy way to run an arbitrary Python script? Essentially, what I want is something like the Windows Run Dialog Box that appears when you press Win-R, which can run any program on the system PATH.

like image 855
Al Sweigart Avatar asked Mar 16 '19 05:03

Al Sweigart


People also ask

Can I run Python in Ubuntu terminal?

If you are curious about how to run Python in Ubuntu, here's an article dedicated for it which may help you out. We are here using Ubuntu Version 14.04. It supports Python 2 and Python 3 versions.

How do I run a .py file in terminal?

Using the python Command To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


1 Answers

(Tested on 18.04) Create this file in ~/.local/share/applications (for use only by your user) or in /usr/share/applications (for use by all users).
The file name must end in .desktop.

[Desktop Entry]
Name=hello.py
Exec=/path/to/hello.py
Type=Application
Categories=GTK;GNOME;Utility;

Note that the script runs in the background, and errors are swallowed unless you configure logging to a file within your script.

If you want it to run in a console, you could do this (the console will close when the script exits, though):

[Desktop Entry]
Name=hello.py
Exec=gnome-terminal -- /path/to/hello.py
Type=Application
Categories=GTK;GNOME;Utility;

More features are available if you want icons, to limit what desktop environments it runs under, etc - docs here: https://developer.gnome.org/integration-guide/stable/desktop-files.html.en

assumptions:

  • hello.py is executable by the current user
  • hello.py has a valid shebang
  • the path needs to be an absolute path (i.e. not relative and also not using shell expansions such as ~ or variables)
like image 166
Bengerman Avatar answered Oct 16 '22 22:10

Bengerman