Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: syntax error with import

I have a python script technically named /home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_BMP085/Adafruit_BMP085_example.py

The first line of this script is

from Adafruit_BMP085 import BMP085

Also located in this directory is a python file named Adafruit_BMP085 that has a function BMP085.

I want to create a python script in /home/pi that imports the same BMP085.

I've tried:

from /home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_BMP085/Adafruit_BMP085 import BMP085

But this just gives me a syntax error:

SyntaxError: invalid syntax

I've tried various syntax combinations of this same method, but cannot find one that works.

like image 451
user2170780 Avatar asked Mar 14 '13 18:03

user2170780


People also ask

How do I fix invalid syntax error in Python?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

What is the syntax of import in Python?

The Python import statement lets you import a module into your code. A module is a file that contains functions and values that you can reference from your program. The import statement syntax is: import modulename.

What is import error in Python?

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.


2 Answers

You need to add the /home/pi/Adafruit-Raspberry-Pi-Python-Code path to the module search path in sys.path:

import sys

sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code')
from Adafruit_BMP085 import BMP085

or move the Adafruit_BMP085 package to a directory already in your sys.path.

The directory of the script itself is also part of the sys.path, so you could also run:

$ cd /home/pi/Adafruit-Raspberry-Pi-Python-Code
$ cp Adafruit_BMP085/Adafruit_BMP085_example.py .
$ python Adafruit_BMP085_example.py
like image 108
Martijn Pieters Avatar answered Oct 26 '22 19:10

Martijn Pieters


OP's question is generically titled but the post is specific to a particular import case.

In my case, I was getting a SyntaxError when having a very standard import scenario. The error was directly pointing at the import statement, very confusingly.

What was actually happening was that there was a (very subtle) syntax error in the module being imported. Fixing that error resolved the SyntaxError during import.

This was very confusing because Python reported SyntaxError on the import line, rather than forwarding to the internal module's syntax problem (which, I believe, sometimes it does); even a generic ImportError would've been more helpful. I wasted time thinking it was some module/path naming issue.

like image 40
alelom Avatar answered Oct 26 '22 21:10

alelom