Python:导入时出现语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15417415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: syntax error with import
提问by user2170780
I have a python script technically named /home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_BMP085/Adafruit_BMP085_example.py
我有一个技术上命名的 python 脚本 /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.
此目录中还有一个名为 Adafruit_BMP085 的 python 文件,它具有 BMP085 函数。
I want to create a python script in /home/pithat imports the same BMP085.
我想在/home/pi导入相同的 BMP085 中创建一个 python 脚本。
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.
我已经尝试了相同方法的各种语法组合,但找不到有效的组合。
回答by Martijn Pieters
You need to add the /home/pi/Adafruit-Raspberry-Pi-Python-Codepath to the module search path in sys.path:
您需要将/home/pi/Adafruit-Raspberry-Pi-Python-Code路径添加到模块搜索路径中sys.path:
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code')
from Adafruit_BMP085 import BMP085
or move the Adafruit_BMP085package to a directory already in your sys.path.
或将Adafruit_BMP085包移动到sys.path.
The directory of the script itself is also part of the sys.path, so you could also run:
脚本本身的目录也是 的一部分sys.path,因此您还可以运行:
$ cd /home/pi/Adafruit-Raspberry-Pi-Python-Code
$ cp Adafruit_BMP085/Adafruit_BMP085_example.py .
$ python Adafruit_BMP085_example.py
回答by Pieter
I had the same problem. The problem first occured when upgrading to Jessie on RPI. The cause was probably within the pathing. Added below line to Python program:
我有同样的问题。在 RPI 上升级到Jessie时首先出现问题。原因可能在路径之内。在 Python 程序中添加了以下行:
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_BMP085')
Now problem solved.
现在问题解决了。

