Python syntax error when running from bash script - python

I've got a Python script uploaded to a linux machine, which I need to be ran through a bash script. The script runs absolutely fine when I type "python test.py", and it outputs as expected. However when I run the bash script "bash runScript.sh" I get a syntax error.
My python script (It's dead simple):
with open ("TextFiles/10.10.10.10config.txt",'r') as f:
print f
My bash script:
wget --no-check-certificate https://10.10.10.10/config.txt -O /usr/bin/grabber/TextFiles/10.10.10.10config.txt
/usr/bin/python2 /usr/bin/grabber/test.py
The error when I run the bash script states:
File "/usr/bin/grabber/test.py", line 1
with open ("TextFiles/10.87.4.4channel_config.txt",'r') as f:
^
SyntaxError: invalid syntax
Has anyone had this problem before?

Quick solution: change python2 to python2.7 in your script.
The reason, as mentioned in the comments, is that your /usr/bin/python2 is linking to an old version of python in your system.

Again and again.... I'll show you!
[server]$ /usr/local/bin/python2.7 -c "with open('test.py','r') as f: print 'OK'"
OK
[server]$ /usr/local/bin/python2.5 -c "with open('test.py','r') as f: print 'OK'"
<string>:1: Warning: 'with' will become a reserved keyword in Python 2.6
File "<string>", line 1
with open('test.py','r') as f: print 'OK'
^
SyntaxError: invalid syntax
with can be used after python 2.6

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.

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

Syntax error on bash for running python script

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

In Windows 10, how shall I run a python script created and runnable in Ubuntu?

In Windows 10, I added the pathname of the parent directory of a python script toc.py to environment variable PATH. Then I tried to run it in two ways, but both failed:
In cmd
>toc.py -i toc -s syntax -p pn
Unable to create process using 'C:\Users\Tim\AppData\Local\Programs\Python\Python35-32\python.exe "C:\Users\Tim\Downloads\self\bookmark\mine\toc2others.py" -i toc -s syntax -p pn'
In Cygwin
$ toc.py -i toc -p pn -s syntax
C:\Users\Tim\AppData\Local\Programs\Python\Python35-32\python.exe: can't open file '/cygdrive/c/Users/Tim/Downloads/self/bookmark/mine/toc2others.py': [Errno 2] No such file or directory
The python script toc.py was created to run with Python 2.7 under Ubuntu, and it looks like
#! /usr/bin/env python
# -*- coding: utf-8 -*
import pdb
from optparse import OptionParser
...
What shall i do in order to run the python script in cmd ?
What shall i do in order to run the python script in Cygwin?
Thanks.
Update:
i remove the shebang from the python script, and now
>toc.py -i toc -s syntax -p pn
File "C:\Users\Tim\Downloads\self\bookmark\mine\toc.py", line 37
print " "*level, root.value
^
SyntaxError: Missing parentheses in call to 'print'
Is this error because of using Python 3 interpreter and Python 2.7 script?

python -c and `while`

Is there a way to loop in while if you start the script with python -c? This doesn't seem to be related to platform or python version...
Linux
[mpenning#Hotcoffee ~]$ python -c "import os;while (True): os.system('ls')"
File "<string>", line 1
import os;while (True): os.system('ls')
^
SyntaxError: invalid syntax
[mpenning#Hotcoffee ~]$
[mpenning#Hotcoffee ~]$ python -V
Python 2.6.6
[mpenning#Hotcoffee ~]$ uname -a
Linux Hotcoffee 2.6.32-5-amd64 #1 SMP Sun May 6 04:00:17 UTC 2012 x86_64 GNU/Linux
[mpenning#Hotcoffee ~]$
Windows
C:\Users\mike_pennington>python -c "import os;while True: os.system('dir')"
File "<string>", line 1
import os;while True: os.system('dir')
^
SyntaxError: invalid syntax
C:\Users\mike_pennington>python -V
Python 2.7.2
C:\Users\mike_pennington>
I have tried removing parenthesis in the while statement, but nothing seems to make this run.
python -c $'import subprocess\nwhile True: subprocess.call(["ls"])'
would work (note the $'...' and the \n).
But it could be that it only works under bash - I am not sure...
Multiline statements may not start after a statement-separating ; in Python – otherwise, there might be ambiguities about the code blocks. Simply use line breaks in stead of ;. This "works" on Linux:
$ python -c "import os
while True: os.system('ls')"
Not sure how to enter this on Windows, but why not simply write the commands to a .py file if it's more than one line?
Don't know about windows, if all you want is to be able to type in one-liners, you could consider line breaks inside quotes:
% python -c "import os;
while (True):
os.system('ls')"
If you really must do this in windows, you could use exec:
python -c "exec \"import os;\rwhile True:\r os.system('dir')\""
(I substituted dir so it works on my windows system)

Categories

Resources