I need help running python in ubuntu
I can run python without a problem in my terminal
but when I create a .py
file I can't get it to run.
I need help running python in ubuntu
I can run python without a problem in my terminal
but when I create a .py
file I can't get it to run.
How it works (examples for python2
, for python3
, replace all occurrences of python
by python3
):
python /path/to/script.py
#!/usr/bin/env python
) in the head of the script is good practice, but not needed/path/to/script.py
#!/usr/bin/env python
)script.py
#!/usr/bin/env python
)script
#!/usr/bin/env python
)The shell can get its information on how to run a script from two sources (in order of precedence):
python <script>
#!/usr/bin/env python
The language extension however does not play a role(!).
A few examples:
A bash
script, correct (language) information in the command, incorrect shebang, incorrect extension:
#!/usr/bin/env python
echo 'Monkey eats banana'
ran with:
$ sh /path/to/script.py
> Monkey eats banana
runs correctly, the information in the command takes precedence over both the shebang and the extension.
An (executable) python
script, ran with incorrect extension, but a correct shebang:
#!/usr/bin/env/python
print "Monkey eats banana"
ran with:
$ /path/to/script.sh
> Monkey eats banana
runs correctly, the information in the shebang takes precedence over the extension.
An (executable) python
script, with a correct extension, but without shebang (and without language information in the command):
print "Monkey"
Ran with the command:
$ /path/to/script.py
> Error: no such file "Monkey"
does not run correctly, in spite of the language extension!
To run a python script, use python
:
python script.py
~/Desktop
, change its location to ~/Desktop
: in a terminal: cd ~/Desktop
This question is answered here: Running Python File in Terminal
If none of these work:
You can save your code as a script in gedit with a .py file extension ie.exampleFile.py
But on the first line add #!/usr/bin/python
and save.
Make the script executable by entering
chmod +x exampleFile.py
into the terminal.
(I usually save scripts in a separate directory and call the directory in the terminal via cd exampleDirectory
and then execute scripts in that specific directory)
[also you can check if the script is in your directory by entering the l
command in the terminal to list the files in that directory and the script should be green if it executable]
Then you can call the script to be ran in the terminal:
python exampleFile.py
You can replace python
with python3
in all the areas that python
was listed, if you'd rather prefer that version
In addition, you can use vim
or other third party software to write and run python scripts if none of these work.