programing

PyCharm을 PySpark와 연결하는 방법은 무엇입니까?

nasanasas 2020. 11. 7. 10:10
반응형

PyCharm을 PySpark와 연결하는 방법은 무엇입니까?


나는 아파치 스파크를 처음 사용했으며 분명히 내 맥북에 홈브류와 함께 아파치 스파크를 설치했습니다.

Last login: Fri Jan  8 12:52:04 on console
user@MacBook-Pro-de-User-2:~$ pyspark
Python 2.7.10 (default, Jul 13 2015, 12:05:58)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/01/08 14:46:44 INFO SparkContext: Running Spark version 1.5.1
16/01/08 14:46:46 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/01/08 14:46:47 INFO SecurityManager: Changing view acls to: user
16/01/08 14:46:47 INFO SecurityManager: Changing modify acls to: user
16/01/08 14:46:47 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(user); users with modify permissions: Set(user)
16/01/08 14:46:50 INFO Slf4jLogger: Slf4jLogger started
16/01/08 14:46:50 INFO Remoting: Starting remoting
16/01/08 14:46:51 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@192.168.1.64:50199]
16/01/08 14:46:51 INFO Utils: Successfully started service 'sparkDriver' on port 50199.
16/01/08 14:46:51 INFO SparkEnv: Registering MapOutputTracker
16/01/08 14:46:51 INFO SparkEnv: Registering BlockManagerMaster
16/01/08 14:46:51 INFO DiskBlockManager: Created local directory at /private/var/folders/5x/k7n54drn1csc7w0j7vchjnmc0000gn/T/blockmgr-769e6f91-f0e7-49f9-b45d-1b6382637c95
16/01/08 14:46:51 INFO MemoryStore: MemoryStore started with capacity 530.0 MB
16/01/08 14:46:52 INFO HttpFileServer: HTTP File server directory is /private/var/folders/5x/k7n54drn1csc7w0j7vchjnmc0000gn/T/spark-8e4749ea-9ae7-4137-a0e1-52e410a8e4c5/httpd-1adcd424-c8e9-4e54-a45a-a735ade00393
16/01/08 14:46:52 INFO HttpServer: Starting HTTP Server
16/01/08 14:46:52 INFO Utils: Successfully started service 'HTTP file server' on port 50200.
16/01/08 14:46:52 INFO SparkEnv: Registering OutputCommitCoordinator
16/01/08 14:46:52 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/01/08 14:46:52 INFO SparkUI: Started SparkUI at http://192.168.1.64:4040
16/01/08 14:46:53 WARN MetricsSystem: Using default name DAGScheduler for source because spark.app.id is not set.
16/01/08 14:46:53 INFO Executor: Starting executor ID driver on host localhost
16/01/08 14:46:53 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 50201.
16/01/08 14:46:53 INFO NettyBlockTransferService: Server created on 50201
16/01/08 14:46:53 INFO BlockManagerMaster: Trying to register BlockManager
16/01/08 14:46:53 INFO BlockManagerMasterEndpoint: Registering block manager localhost:50201 with 530.0 MB RAM, BlockManagerId(driver, localhost, 50201)
16/01/08 14:46:53 INFO BlockManagerMaster: Registered BlockManager
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 1.5.1
      /_/

Using Python version 2.7.10 (default, Jul 13 2015 12:05:58)
SparkContext available as sc, HiveContext available as sqlContext.
>>>

MLlib에 대해 자세히 알아보기 위해 게임을 시작하고 싶습니다. 그러나 나는 Pycharm을 사용하여 파이썬으로 스크립트를 작성합니다. 문제는 Pycharm으로 이동하여 pyspark를 호출하려고하면 Pycharm이 모듈을 찾을 수 없다는 것입니다. 다음과 같이 Pycharm에 경로를 추가해 보았습니다.

pycharm을 스파크와 연결할 수 없습니다.

그런 다음 블로그에서 이것을 시도했습니다.

import os
import sys

# Path for spark source folder
os.environ['SPARK_HOME']="/Users/user/Apps/spark-1.5.2-bin-hadoop2.4"

# Append pyspark  to Python Path
sys.path.append("/Users/user/Apps/spark-1.5.2-bin-hadoop2.4/python/pyspark")

try:
    from pyspark import SparkContext
    from pyspark import SparkConf
    print ("Successfully imported Spark Modules")

except ImportError as e:
    print ("Can not import Spark Modules", e)
    sys.exit(1)

그리고 PyCharm과 함께 PySpark를 사용할 수 없습니다. PyCharm을 apache-pyspark와 "연결"하는 방법에 대한 아이디어가 있습니까?

최신 정보:

그런 다음 Pycharm의 환경 변수를 설정하기 위해 apache-spark 및 python 경로를 검색합니다.

아파치 스파크 경로 :

user@MacBook-Pro-User-2:~$ brew info apache-spark
apache-spark: stable 1.6.0, HEAD
Engine for large-scale data processing
https://spark.apache.org/
/usr/local/Cellar/apache-spark/1.5.1 (649 files, 302.9M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/apache-spark.rb

파이썬 경로 :

user@MacBook-Pro-User-2:~$ brew info python
python: stable 2.7.11 (bottled), HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org
/usr/local/Cellar/python/2.7.10_2 (4,965 files, 66.9M) *

그런 다음 위의 정보를 사용하여 다음과 같이 환경 변수를 설정하려고했습니다.

구성 1

Pycharm을 pyspark와 올바르게 연결하는 방법에 대한 아이디어가 있습니까?

그런 다음 위의 구성으로 파이썬 스크립트를 실행할 때 다음 예외가 있습니다.

/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/user/PycharmProjects/spark_examples/test_1.py
Traceback (most recent call last):
  File "/Users/user/PycharmProjects/spark_examples/test_1.py", line 1, in <module>
    from pyspark import SparkContext
ImportError: No module named pyspark

업데이트 : 그런 다음 @ zero323이 제안한이 구성을 시도했습니다.

구성 1 :

/usr/local/Cellar/apache-spark/1.5.1/ 

conf 1

밖:

 user@MacBook-Pro-de-User-2:/usr/local/Cellar/apache-spark/1.5.1$ ls
CHANGES.txt           NOTICE                libexec/
INSTALL_RECEIPT.json  README.md
LICENSE               bin/

구성 2 :

/usr/local/Cellar/apache-spark/1.5.1/libexec 

여기에 이미지 설명 입력

밖:

user@MacBook-Pro-de-User-2:/usr/local/Cellar/apache-spark/1.5.1/libexec$ ls
R/        bin/      data/     examples/ python/
RELEASE   conf/     ec2/      lib/      sbin/

PySpark 패키지 사용 (Spark 2.2.0 이상)

함께 SPARK-1267 존재가 합병 당신으로 과정을 단순화 할 수 있어야한다 pip당신이 PyCharm 개발을 위해 사용하는 환경에서 스파크를 설치.

  1. 이동 파일 -> 설정 -> 프로젝트 통역
  2. 설치 버튼을 클릭하고 PySpark를 검색하십시오.

    여기에 이미지 설명 입력

  3. 패키지 설치 버튼을 클릭하십시오.

사용자 제공 Spark 설치를 사용하여 수동으로

실행 구성 만들기 :

  1. 실행 -> 구성 편집으로 이동 하십시오.
  2. 새 Python 구성 추가
  3. 실행할 스크립트를 가리 키도록 스크립트 경로 설정
  4. 최소한 다음을 포함하도록 환경 변수 필드를 편집하십시오 .

    • SPARK_HOME-Spark가 설치된 디렉토리를 가리켜 야합니다. 그것은 다음과 같은 디렉토리를 포함해야한다 bin(와 spark-submit, spark-shell등,)과 conf(와 spark-defaults.conf, spark-env.sh등)
    • PYTHONPATH-포함해야하며 그렇지 않은 경우 $SPARK_HOME/python선택적으로 $SPARK_HOME/python/lib/py4j-some-version.src.zip사용할 수 없습니다. some-version지정된 Spark 설치에서 사용하는 Py4J 버전과 일치해야합니다 (0.8.2.1-1.5, 0.9-1.6, 0.10.3-2.0, 0.10.4-2.1, 0.10.4-2.2, 0.10.6-2.3, 0.10.7-2.4) )

      여기에 이미지 설명 입력

  5. 설정 적용

인터프리터 경로에 PySpark 라이브러리를 추가합니다 (코드 완성에 필요) :

  1. 이동 파일 -> 설정 -> 프로젝트 통역
  2. Spark에서 사용할 인터프리터에 대한 설정 열기
  3. 인터프리터 경로를 편집하여 경로를 포함합니다 $SPARK_HOME/python(필요한 경우 Py4J).
  4. 설정 저장

선택적으로

  1. 더 나은 완료 및 정적 오류 감지를 위해 설치된 Spark 버전과 일치하는 경로 유형 주석 을 설치하거나 추가합니다 (면책 조항-프로젝트 작성자입니다).

드디어

새로 생성 된 구성을 사용하여 스크립트를 실행합니다.


Mac OSX에서이 문제를 해결 한 방법은 다음과 같습니다.

  1. brew install apache-spark
  2. 이것을 ~ / .bash_profile에 추가하십시오.

    export SPARK_VERSION=`ls /usr/local/Cellar/apache-spark/ | sort | tail -1`
    export SPARK_HOME="/usr/local/Cellar/apache-spark/$SPARK_VERSION/libexec"
    export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
    export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH
    
  3. 콘텐츠 루트에 pyspark 및 py4j를 추가합니다 (올바른 Spark 버전 사용).

    /usr/local/Cellar/apache-spark/1.6.1/libexec/python/lib/py4j-0.9-src.zip
    /usr/local/Cellar/apache-spark/1.6.1/libexec/python/lib/pyspark.zip
    

여기에 이미지 설명 입력


저에게 적합한 설정은 다음과 같습니다 (Win7 64bit, PyCharm2017.3CE).

Intellisense 설정 :

  1. 파일-> 설정-> 프로젝트 :-> 프로젝트 해석기를 클릭하십시오.

  2. 프로젝트 인터프리터 드롭 다운 오른쪽에있는 톱니 바퀴 아이콘을 클릭합니다.

  3. 상황에 맞는 메뉴에서 자세히 ...를 클릭합니다.

  4. 인터프리터를 선택한 다음 "경로 표시"아이콘 (오른쪽 하단)을 클릭합니다.

  5. + 아이콘 2를 클릭하여 다음 경로를 추가하십시오.

    \ python \ lib \ py4j-0.9-src.zip

    \ bin \ python \ lib \ pyspark.zip

  6. 확인, 확인, 확인을 클릭하십시오.

계속해서 새로운 인텔리전스 기능을 테스트하십시오.


pycharm에서 pyspark 구성 (Windows)

File menu - settings - project interpreter - (gearshape) - more - (treebelowfunnel) - (+) - [add python folder form spark installation and then py4j-*.zip] - click ok

Windows 환경에 SPARK_HOME이 설정되어 있는지 확인하십시오. pycharm이 거기에서 가져옵니다. 확인 :

Run menu - edit configurations - environment variables - [...] - show

선택적으로 환경 변수에 SPARK_CONF_DIR을 설정합니다.


다음 페이지를 참조로 사용했으며 PyCharm 5에서 가져온 pyspark / Spark 1.6.1 (homebrew를 통해 설치됨)을 가져올 수있었습니다.

http://renien.com/blog/accessing-pyspark-pycharm/

import os
import sys

# Path for spark source folder
os.environ['SPARK_HOME']="/usr/local/Cellar/apache-spark/1.6.1"

# Append pyspark  to Python Path
sys.path.append("/usr/local/Cellar/apache-spark/1.6.1/libexec/python")

try:
    from pyspark import SparkContext
    from pyspark import SparkConf
    print ("Successfully imported Spark Modules")
except ImportError as e:
    print ("Can not import Spark Modules", e)
sys.exit(1)

With the above, pyspark loads, but I get a gateway error when I try to create a SparkContext. There's some issue with Spark from homebrew, so I just grabbed Spark from the Spark website (download the Pre-built for Hadoop 2.6 and later) and point to the spark and py4j directories under that. Here's the code in pycharm that works!

import os
import sys

# Path for spark source folder
os.environ['SPARK_HOME']="/Users/myUser/Downloads/spark-1.6.1-bin-hadoop2.6"

# Need to Explicitly point to python3 if you are using Python 3.x
os.environ['PYSPARK_PYTHON']="/usr/local/Cellar/python3/3.5.1/bin/python3"

#You might need to enter your local IP
#os.environ['SPARK_LOCAL_IP']="192.168.2.138"

#Path for pyspark and py4j
sys.path.append("/Users/myUser/Downloads/spark-1.6.1-bin-hadoop2.6/python")
sys.path.append("/Users/myUser/Downloads/spark-1.6.1-bin-hadoop2.6/python/lib/py4j-0.9-src.zip")

try:
    from pyspark import SparkContext
    from pyspark import SparkConf
    print ("Successfully imported Spark Modules")
except ImportError as e:
    print ("Can not import Spark Modules", e)
    sys.exit(1)

sc = SparkContext('local')
words = sc.parallelize(["scala","java","hadoop","spark","akka"])
print(words.count())

I had a lot of help from these instructions, which helped me troubleshoot in PyDev and then get it working PyCharm - https://enahwe.wordpress.com/2015/11/25/how-to-configure-eclipse-for-developing-with-python-and-spark-on-hadoop/

I'm sure somebody has spent a few hours bashing their head against their monitor trying to get this working, so hopefully this helps save their sanity!


I use conda to manage my Python packages. So all I did in a terminal outside PyCharm was:

conda install pyspark

or, if you want an earlier version, say 2.2.0, then do:

conda install pyspark=2.2.0

This automatically pulls in py4j as well. PyCharm then no longer complained about import pyspark... and code completion also worked. Note my PyCharm project was already configured to use the Python interpreter that comes with Anaconda.


Check out this video.

Assume your spark python directory is: /home/user/spark/python

Assume your Py4j source is: /home/user/spark/python/lib/py4j-0.9-src.zip

Basically you add the the spark python directory and the py4j directory within that to the interpreter paths. I don't have enough reputation to post a screenshot or I would.

In the video, the user creates a virtual environment within pycharm itself, however, you can make the virtual environment outside of pycharm or activate a pre-existing virtual environment, then start pycharm with it and add those paths to the virtual environment interpreter paths from within pycharm.

I used other methods to add spark via the bash environment variables, which works great outside of pycharm, but for some reason they weren't recognized within pycharm, but this method worked perfectly.


You need to setup PYTHONPATH, SPARK_HOME before you launch IDE or Python.

Windows, edit environment variables, added spark python and py4j into

PYTHONPATH=%PYTHONPATH%;{py4j};{spark python}

Unix,

export PYTHONPATH=${PYTHONPATH};{py4j};{spark/python}

From the documentation:

To run Spark applications in Python, use the bin/spark-submit script located in the Spark directory. This script will load Spark’s Java/Scala libraries and allow you to submit applications to a cluster. You can also use bin/pyspark to launch an interactive Python shell.

You are invoking your script directly with the CPython interpreter, which I think is causing problems.

Try running your script with:

"${SPARK_HOME}"/bin/spark-submit test_1.py

If that works, you should be able to get it working in PyCharm by setting the project's interpreter to spark-submit.


I followed the tutorials on-line and added the env variables to .bashrc:

# add pyspark to python
export SPARK_HOME=/home/lolo/spark-1.6.1
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH

I then just got the value in SPARK_HOME and PYTHONPATH to pycharm:

(srz-reco)lolo@K:~$ echo $SPARK_HOME 
/home/lolo/spark-1.6.1
(srz-reco)lolo@K:~$ echo $PYTHONPATH
/home/lolo/spark-1.6.1/python/lib/py4j-0.9-src.zip:/home/lolo/spark-1.6.1/python/:/home/lolo/spark-1.6.1/python/lib/py4j-0.9-src.zip:/home/lolo/spark-1.6.1/python/:/python/lib/py4j-0.8.2.1-src.zip:/python/:

Then I copied it to Run/Debug Configurations -> Environment variables of the script.


The simplest way is to install PySpark through project interpreter.

  1. Go to File - Settings - Project - Project Interpreter
  2. Click on the + icon on top right.
  3. Search for PySpark and other packages you want to install
  4. Finally click install package
  5. Its Done!!

The easiest way is

Go to the site-packages folder of your anaconda/python installation, Copy paste the pyspark and pyspark.egg-info folders there.

Restart pycharm to update index. The above mentioned two folders are present in spark/python folder of your spark installation. This way you'll get code completion suggestions also from pycharm.

The site-packages can be easily found in your python installation. In anaconda its under anaconda/lib/pythonx.x/site-packages


프로젝트 인터프리터 메뉴를 통해 pyspark 모듈을 추가하려고했지만 충분하지 않았습니다 ... 로컬 데이터 파일을 읽기 위해 설정해야하는 많은 시스템 환경 변수 SPARK_HOME와 경로가 /hadoop/bin/winutils.exe있습니다. 또한 시스템 환경 변수 및 .NET Framework에서 모두 사용할 수있는 올바른 버전의 Python, JRE, JDK를 사용해야합니다 PATH. 인터넷 검색을 많이 한 후이 비디오 지침이 작동했습니다.

참고 URL : https://stackoverflow.com/questions/34685905/how-to-link-pycharm-with-pyspark

반응형