Syntax error on bash for running python script - python

I want run this simple python code int terminal:
#!/usr/bin/env python3
print('Hello world')
I saved this script as hello.py
I go to terminal to write down:
$ chmod +x hello.py
then I click enter. This is to allow permission to be granted. Terminal then showed me this:
-bash: $: command not found
Ok...I then write down the path to hello.py:
$ /Users/myname/Documents/MyPythonScripts/hello.py
I press enter. I was expecting terminal to print out hello world but to my horror, terminal show this:
/Users/myname/Documents/MyPythonScript/hello.py: line 3: syntax error near unexpected token `'Hello world''
/Users/hadi/Documents/MyPythonScript/hello.py: line 3: `print('Hello world')'
What's wrong here?
Btw, Running on macOS 10.13.3 and Python 3.6.3

First of all, this line:
-bash: $: command not found
tells that you've executed the "$" which is not right.
Your command to set permissions should look like this:
chmod +x hello.py
Another comment is that the shebang line should be without space:
#!/usr/bin/env python3

Related

How to get python via virtual environment recognized in bash file via shebang

I have a script file:
#!/usr/bin/env python3.9
print("python is working")
However when I try and run it:
(karl-env) karl#Karls-MBP scripts (karl/test) $ . test.sh
bash: test.sh: line 3: syntax error near unexpected token `"python is working"'
bash: test.sh: line 3: `print("python is working")'
Following info:
(karl-env) karl#Karls-MBP scripts (karl/test) $ type -a python
python is /Users/karl/.pyenv/shims/python
python is /Users/karl/.pyenv/shims/python
python is /usr/bin/python
I'm in a virtual environment but I fail to understand how to get my environments python recognized via the shebang #!/usr/bin/env python3.9. I do not use Python often hence my noobiness!
This has a little to do with Python and a lot to do with the shell.
You're doing . test.sh – . is an alias for source, which has your shell attempt to interpret the given script as shell commands you'd enter. You want ./test.sh to execute the script.
Your shebang line is explicitly looking for a python3.9 executable, and your environment might not be Python 3.9, so you fall back to something else. Do python (or python3) instead: #!/usr/bin/env python
For the sake of sanity, rename your script to .py; it's not a .shellscript.

Unable to open my source code a second time with `python -i`

When I first start bash I can open my code like so:
$ python -i index.py
That file is open, but when I try again this happens:
>>> python -i index.py
File "<stdin>", line 1
python -i index.py
^
SyntaxError: invalid syntax
If I close bash and start again it works. What am I doing wrong?
You can't run terminal commands from the Python REPL.
You can tell you're in the REPL when you see >>> as opposed to $. This means you can run Python code there, but not shell/terminal commands (like the python command).
To exit the REPL, use Ctrl + Z or type exit() and press enter. This will bring you back to the regular terminal.
In addition, I'd recommend running just python index.py rather than python -i index.py in most cases.
The added -i means that you'd like to stay in the REPL to inspect the results after running the index.py file. It allows you to continue running additional Python code after the index.py file has finished its execution.
It looks by the three >>> that you are in the python console not in bash itself. If you type exit() you should get back to bash, and then you can try the code again.

Executing python module with Click command using command line

I have created a directory 'prince' which consists of a subdirectory 'src' containing 'main.py' file in it. This main.py uses Click command for input from user using command line. So currently I have to set current working directory to 'prince' in terminal and then execute my module using the command
'$ python -m src.main run --s 10 20 30'
where 'run', '--s' are my click command inputs.
Is there an easy way to wrap 'python -m src.main' to something short to execute my module along with inputs using click command ? Or any better way to execute my module along with inputs from user ?
I hope this will answer your question.
In your src/main.py file you could add a #!/usr/bin/env python3 shebang which means that your program is run by python by default.
And you should give it execute permissions via
chmod +x src/main.py
That means you can now run
src/main run --s 10 20 30
Instead of
$ python -m src.main run --s 10 20 30
Antother way to achieve this would be:
Create a file in the "prince" directory named "start" with Content:
python3 -m src.main "$#"
Give it executable permissions:
chmod +x start
Now you can run:
./start run --s 10 20 30

Python script runs on command line but not from .sh file

I'm attempting to create a .sh file to batch a number of runs of a neural network on Python whilst on holidays.
At the moment I have been calling this from the command line:
python neural_network_trainer.py [args]
I now have a .sh script written:
#!/bin/bash
python neural_network_trainer.py [args]
# Repeated with varied args
That I am attempting to call in the same terminal as the original command line was running:
./august_hols.sh
I get the following error:
File "/data/Python-3.6.9/lib/python3.6/site.py", line 177
file=sys.stderr)
^
SyntaxError: invalid syntax
Where the Python install is in /data (for reasons).
Running which on the command line reports the correct Python directory set via an alias in ~/.bashrc:
alias python=/data/Python-3.6.9/bin/python3
But running which between the Bash shebang and the first python call reports /bin/python.
I've attempted to set the alias again at the start of the .sh script to no avail. I'm scratching my head as this is exact process I have used elsewhere, albeit not on this precise PC. I can copy the exact command from the top of the bash file into the terminal and it runs fine, try and call ./august_hols.sh and get the above Python error.
Where is Bash getting that path from, and why is it not using my expected route through ~/.bashrc?
Bash sub-shell does not inherit alias in the main shell
You can source the script (run in the main shell), instead of execute it (run in the sub-shell)
source script.sh
EDIT:
Solution 2:
Run bash as the login shell so ~/.bashrc is executed, so your alias is loaded before your script.
The subshell needs to be interactive to enable alias, because alias is enabled by default only for interactive shell, but script is non-interactive by default.
bash --login -i script.sh
Solution 3:
Similar to above, except alias is enabled explicitly
bash --login -O expand_aliases script.sh
Have you tried:
python=/data/Python-3.6.9/bin/python3 ./[your_bash].sh
In your .sh
Do this
#!/usr/bin/env bash
export PATH=/data/Python-3.6.9/bin:$PATH
exec python neural_network_trainer.py "$#"
Aliases are tricky.
A maybe more nasty solution
mapfile < <(declare -p | grep -m 1 BASH_ALIASES) && bash script.sh "${MAPFILE[#]}"
within your script you will need
shopt -s expand_aliases
eval $1
echo ${BASH_ALIASES[python]}
python --version
How about this:
#!/bin/bash
/data/Python-3.6.9/bin/python3 neural_network_trainer.py [args]
# Repeated with varied args

Altering my python path: helloworld.py returns command not found—

Massive apologies for this embarrassing question—
I'm using my MacBook Pro, running snow leopard, and using Python 2.7.1. Trying to run my first script and all the first pages of all my tutorials are laughing at me:
Let me preface with:
$ whereis python
/usr/bin/python
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
(Is this my issue?)
I wrote helloworld.py to /users/charles in vim:
$ vim helloworld.py
#!/usr/bin/python
# Hello World Python Program
print "Hello World!";
When trying to run it from terminal:
$ helloworld.py
-bash: helloworld.py: command not found
When trying to run it from python:
$ python
>>> helloworld.py
Traceback (most recent call last):
File :<stdin>", line 1, in <module>
NameError: name 'helloworld' is not defined
From Dive Into Python (not sure if this is pertinent):
$ python
>>> import sys,os
>>> print 'sys.argv[0] =',sys.argv[0]
sys.argv[0]=
>>> pathname=os.path.dirname(sys.argv[0])
>>> print 'path=',pathname
path=
>>> print 'full path=',os.path.abspath(pathname)
full path= /Users/charles
I'm befuddled! Do I need to alter one of my paths so it finds my script?
I'm absolutely new to programming, I actually just found out that terminal was something you could use.
Thanks!
Let's start with the first error you received. Understanding error messages is important.
-bash: helloworld.py: command not found
This indicates that helloworld.py is not a command that can be executed. To run the file, you then have two options:
Run it using the python interpreter. python helloworld.py
Make the file executable and then run it directly. ./helloworld.py
To make files executable in a *nix environment, you have to change their mode to allow execution. In order to do this, you use the chmod command (man chmod for more info).
chmod +x helloworld.py
This assumes that you are in the directory containing the helloworld.py file. If not, cd there first or use the full path.
The ./ is necessary because it tells the shell to run the file located here, not by looking in $PATH. $PATH is a list of possible executable locations. When you try to run helloworld.py directly, the shell tries to look for it in $PATH. You want to run the local file, so you have to prefix it with ./, which means "from here".
As an aside, note the first line of your python script:
#!/usr/bin/python
This is called a shebang line and tells system to use the /usr/bin/python executable to load the file. Internally, that means that the program loader will be doing /user/bin/python helloworld.py.
Finally, when you called python with no arguments, you were dropped into an interactive Python interpreter session. >>> helloworld.py in this environment is not referencing the file of that name, it's just interpreted as python code. Invalid python code. This is why you get your second error, NameError: name 'helloworld' is not defined.
To turn a Python module or script into a standalone program on a UNIX system you have to do two things:
1.) Make sure you have the "shebang" in the top of your script:
#!/usr/bin/python
2.) Make sure the script file is executable. This is done using the chmod command:
chmod +x /path/to/helloworld.py
/path/to/ being the fully qualified file path to your script. If it's in the current directory, then you can omit the path.
% ls -l
total 0
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rw-r--r-- 1 jathan jathan 0 2011-04-13 15:28 helloworld.py
It's in my current directory, so let's make it executable!
% chmod +x helloworld.py
% ls -l
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rwxr-xr-x 1 jathan jathan 0 2011-04-13 15:28 helloworld.py*
See the "x"s in the permission bits on the left? You've done it! Now we can run it:
% ./helloworld.py
Hello World!
Lastly, never use semicolons as line-endings in Python. It's not required and it's ugly!
Wanted to add my 2 cents: Apart from permissions and path answers above, there is one more situation where you may still face the same error.
In-spite of correct permissions and the shebang header, you may still get the same "Command not found" error if you've originally written the file in Windows and copied it over to Linux. Due to differing line-ending characters, there will be extra '\r' characters on the lines.
This happens because there are non-printable characters in the file. Examing it by doing:
cat -v <filename>:
#!/usr/intel/bin/python^M
The extra "^M" is the problem. Use 'dos2unix' to convert the file and then it'll run fine.
as others said you should chmod +x your file to make it executable and if you don't want to put "./" in your coomand line you should add your current place as system path:
export PATH=$PATH:.
If you're already within python, the syntax to load your script is not helloworld.py :
import helloworld
or
from helloworld import *
you only use the extension .py when you're running python with a script as a command line argument.
No need to apologize, have to start somewhere, and the error messages can be cryptic when you're having basic syntax problems.
Make sure your terminal's current working directory is where your .py file is.
EDITED:
try doing /usr/bin/python helloworld.py on commmand line

Categories

Resources