When I attempted to execute a Python script today on a CentOS Linux system from a shell prompt with
./check.py
, I received the following error message:
import: unable to open X server `' @ error/import.c/ImportImageCommand/369.
The first line of code I had in the file I was attempting to run was as follows:
import json
It has been quite a while since I created a Python script, but the line
looked fine to me and I couldn't understand why the
JSON library
wasn't being imported, but, instead, the import command seemed to be producing
an error message. I believe that library has been available for use
with Python since Python 2.6 and the system on which I was attempting
to execute the script had Python 2.7.5 on it (you can find the version
from a shell prompt by issuing the command python --version
).
Eventually I realized, I had forgotten to put the
shebang line as the first line in the file. The shebang line, which
starts with #!
tells the shell, in this case the
Bash
shell, which program to use to interpret the rest of the file. When
I put the following line as the first line in the file, that fixed the problem.
#!/bin/python
I could have run the script successfully without that line, if I used
python check.py
. But when I attempted to execute the
script from the command line without making it an argument to the python command, the shell
was interpreting the code, rather than Python.