I have two python installations, one at /usr/bin/env and one through Enthought at /Library/Enthought/User/bin/python. The enthought installation has a library that I would like to use in a website that I've inherited from a former coworker.
I set up a local server through apache on my Mac OSX 10.10.5 (Yosemite). I configured httpd.conf and my user configuration file inside of the website folder to execute cgi and py files.
However, when I try to run my coworker's python scripts through the server, it seems to use the installation without the package I need (/usr/bin/env). I tried changing the shebang at the top of the script from:
'#!/usr/bin/env python'
to
'#!/Library/Enthought/User/bin/ python'
but that gives me an internal service error (500).
One thing I was able to do was to create a symlink using this command:
'sudo ln -s /Library/Enthought/User/bin/python /usr/bin/python'
Now his script can run and has no trouble finding the right python package. However, I'd like to understand why changing the shebang isn't enough. Why does the server still access the /usr/bin/env python distribution?
A subquestion:
Lastly, I created my own test script in the meantime, but I get an Internal Service Error (500) no matter what the shebang is. This script is in the same folder as his script. Why can't this script run?:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgi
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print
print "<html><head>"
print ""
print "</head><body>"
print "Hello."
print "</body></html>"
Thanks! I hope this question was clear. This is my first experience with web servers, so please correct me if I made any terminology mistakes!
The shebang life you quote doesn't work because of the space at the end. /usr/bin/env is a program, and python is the argument, the name of the program it's supposed to look for. Remove the space from your new shebang and you will be running the Python interpreter directly. There's no need to provide it with an argument.
As to why the other script isn't working, I can only guess that you haven't made it executable, since I can't find any other reason for its failure (but this is a guess).
Your second print statement does not have an argument. Try changing it from print to print "\n".
EDIT
Try the following script with the appropriate shebang line prepended and, as holdenweb says, make sure it has execute permissions for the right user. Another issue I have run into in the past is with line terminations. If you have the "od" utility, run "od -c <filename>" on the command line to do an octal dump for your new file and the existing, working file. That way, you can see if the files end with the same line termination("\r\n" or "\n").
import cgi
print "HTTP/1.0 Status: 200 OK"
print "Content-type: text/html"
print ""
print "<html><head>"
print "</head><body>"
print "Hello."
print "</body></html>"
Note the addition of print "HTTP/1.0 Status: 200 OK". Other than that...I am out of suggestions.
Related
I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell
I am new to both Python and Linux and as such request simple explanations with minimal assumed knowledge where possible please, however I am more than willing to invest time and effort to learn.
I have a Raspberry Pi 2 (Model B V1.1) that is running Linux. I interact with this pi via putty.
I am trying to create a simple competitive reflex game, consisting of 2 buttons and a single LED. My goal is to have the LED light up after a short interval, and the first player to press their button wins.
I am writing the script for this with python (specifically 2.7.3)
My issue is that i am unable to run ANY .py file from within putty, i always receive the same error:
Syntax error: word unexpected (expecting ")")
To determine if the issue was an error in my code, i created a very very simple .py file, to check if the same error occurs, and it did. So i currently believe even if my code was functional, something is stopping me from running ANY .py file.
The process I am using is as follows:
First I create a new python file from within putty:
sudo nano test.py
Next I enter my python code (very simple for now, as i cannot get ANY .py file to run)
for each in range(5):
print 'hello'
I then press CTRL + O to write the file, hit enter, then CTRL + X to exit
Finally, I make the file executable using
sudo chmod u+x test.py
and try to run it
sudo ./test.py
again, a similar error occurs
Syntax error: "(" unexpected
I then decided to enter the code directly into the python shell, using
sudo python
>>>for each in range(5):
... print 'hello'
This time the output is the desired outcome:
hello
hello
hello
hello
hello
So there is no problem in executing python code directly from the shell, I am just unable to execute any previously saved .py file
Any insight into what could be causing this is much appreciated, and I apologise if I have not provided enough information to be useful for you.
Thanks in advance!
Short answer: Either run these as python filename.py, or else add the line #!/usr/bin/python to the top of your Python scripts.
Long answer: When you run a file from the command line in Linux (which is what the Raspberry Pi is running), by default it assumes that the file is a shell script file (usually Bash script). So it uses the Bash shell (or some other shell, but it's usually Bash) to interpret the file, and Bash doesn't know Python syntax. If you want to run your file using a different interpreter (Python, in this case), you have to add a "magic line" at the top of the file starting with #! (usually pronounced "hash-bang", and sometimes pronounced "shebang" for short). Following the #! characters is the full path of the interpreter to use, e.g. /usr/bin/python for Python scripts. (You can also use /usr/bin/env python as another answer suggested; I prefer /usr/bin/python because it's impossible to get the wrong Python interpreter that way. But that's getting into advanced topics that may be more than you need right now.)
So when you put the line #!/usr/bin/python at the top of your Python scripts, you're telling the Linux system which interpreter to run the program with, and then it should All Just Work™.
Also, STOP using sudo to edit and run these! That's just asking for trouble.
If you wish to execute like this you need the following line as the first line
#!/usr/bin/env python
This will tell bash (or equivalent) to execute the file with the Python interpreter.
If you don't want to do that then you can execute the script like this:
$ python test.py
If you go this route then you don't need to grant execute permissions on the script itself.
Also, scripts shouldn't be executed with sudo unless absolutely necessary.
I am trying to run this script on my server.
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
I have that code in a python file. I uploaded the file to cgi-bin folder. I then set permission's so every box was ticked (Full Permission). I then attempted to view the page. But I get the error below.
500: Internal server error
This error is generated when a script running on the server could not be implemented or permissions are incorrectly assigned for files or directories
Troubleshooting suggestions:
Temporarily disable any rewrite rules by renaming your .htaccess file if it exists.
Ensure that any CGI or Perl scripts have at least .755. permissions.
If trying to run PHP and you get this error, you may have an invalid php.ini in your /cgi-bin, or may be missing your php.dat file in this folder.
How can I fix this so I can start writing scripts an get on with my website?
All the code does is "Hello World", the script work on other servers. What has a php.dat got to do with me an my python. How am I meant to understand a PHP file when it's half in machine language.... E.g.
Ü™ ì™ ð™ ô™ ø™ ü™ š
š
PHP is irrelevant in this case. It's mentioned in case you are using PHP, but you are not, so you can ignore it.
There are so many possible causes of this error so start at the beginning and work your way through.
First thing to check is the server error log files, if you have access to them they will likely reveal the problem straight away.
Next check whether your server is properly configured to run .py scripts as cgi. Also, check the cgi-bin directory permissions.
Verify that the python binary is located at /usr/bin/python on the server. BTW, a better alternative "shebang" is:
#!/usr/bin/env python
because it is less sensitive to path.
Errors in the code can also cause http 500. Your code works fine for Python 2. It's unlikely, but the server might be using Python 3?
From the other question you say that you are using Python 3.4. The script that you show will run in Python 2, but not in Python 3 because the syntax of the print statement has changed - it is now a function.
To fix the script so that it will run in Python 3, change all of your print statements into functions:
#!/usr/bin/env python
print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('<title>Hello Word - First CGI Program</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! This is my first CGI program</h2>')
print('</body>')
print('</html>')
I have also changed the "shebang" at the top of the script to run whichever python is on the path.
If this doesn't fix the problem, look at the suggestions that I made in my previous answer, i.e. look in the server logs for errors, check your file and directory permissions, make sure that you are running the correct Python version etc.
Finally, talk to your hosting provider - I am sure that they can advise you how to set it up properly and there probably will be instructions on their site - find them and follow them.
My coworker is having trouble with a Python install. When running the code below, from 'C:\my\folder\', 'C:\' is returned instead of the current working directory. When I or anyone else run the script on our systems, we get 'C:\my\folder\'.
We're assuming that some global setting must be causing the issue, so I've had the person uninstall Python, delete the local Python2.7 folder, clean the registry and reinstall the Python, but it's still not working.
NOTE: We have a large number of legacy scripts, so revising all of them to use subprocess is impractical. :(
Any ideas?
Environment: Windows XP, Python 2.7
import os
#
# This test script demonstrates issue on the users computer when python invokes
# a subshell via the standard os.system() call.
#
print "This is what python thinks the current working directory is..."
print os.getcwd()
print
print
print "but when i execute a command *from* python, this is what i get for the current working directory"
os.system('echo %cd%')
raw_input()
you could also try something like this
os.chdir("C:\\to\\my\\folder")
print os.system("echo %CD%")
raw_input()
also to get the current working directory i use a different approach
cur_dir = os.path.abspath(".")
os.getcwd() isn't guarenteed to get the location of your script when it is called. Your coworker might be calling the script a different way or his computer (for some reason) handles the current working directory differently.
To get the actual script location you should use the following:
import os
os.path.dirname(os.path.realpath(__file__))
As an example I wrote getcwd and the above line in the same script and ran it from C:\.
Results:
C:\>python C:\Users\pies\Desktop\test.py
C:\Users\pies\Desktop
C:\
It depends on what your real purpose for this script is, whether you actually need the current working directory, or just the current scripts directory. As a little caveat this call will return a different directory if you call a script from script which then uses this call.
os.system("cd dir;command params")
I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell