복붙노트

[PYTHON] win7 (r 2.12, Python 2.5)에서 rpy2 설치 문제

PYTHON

win7 (r 2.12, Python 2.5)에서 rpy2 설치 문제

저는 파이썬에 대해 아주 새로운 것입니다. (그리고 일반적으로 프로그래밍) 저는 재무 배경에서 왔기 때문에 저와 함께하시기 바랍니다. 방금 통계 분석을 위해 Python (Enthought 's Pylab / Scipy / Numpy)과 R을 사용하기 시작했습니다. R을 통합하기 위해 Python에 rpy2를 설치하려고하는데 오류가 발생합니다.

나는 이것이 무엇을 의미하는지 모른다. 내 R.exe의 경로는 "C : \ Program Files \ R \ R-2.12.1 \ bin"입니다. 어떤 도움을 많이 주시면 감사하겠습니다!

여기에 setup.py 코드가 있습니다.

import os, os.path, sys, shutil, re, itertools
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.build import build as _build

from distutils.core import setup
from distutils.core import Extension


pack_name = 'rpy2'
pack_version = __import__('rpy').__version__


class build(_build):
    user_options = _build.user_options + \
        [
        #('r-autoconfig', None,
        # "guess all configuration paths from " +\
        #     "the R executable found in the PATH " +\
        #     "(this overrides r-home)"),
        ('r-home=', None, 
         "full path for the R home to compile against " +\
             "(see r-autoconfig for an automatic configuration)"),
        ('r-home-lib=', None,
         "full path for the R shared lib/ directory " +\
             "(<r-home>/lib otherwise)"),
        ('r-home-modules=', None,
         "full path for the R shared modules/ directory " +\
             "(<r-home>/modules otherwise)") 
        ]
    boolean_options = _build.boolean_options #+ \
        #['r-autoconfig', ]


    def initialize_options(self):
        _build.initialize_options(self)
        self.r_autoconfig = None
        self.r_home = None
        self.r_home_lib = None
        self.r_home_modules = None

class build_ext(_build_ext):
    """
    -DRPY_VERBOSE
    -DRPY_DEBUG_PRESERV
    -DRPY_DEBUG_PROMISE    : evaluation of promises
    -DRPY_DEBUG_OBJECTINIT : initialization of PySexpObject
    -DRPY_DEBUG_CONSOLE    : console I/O
    -DRPY_DEBUG_COBJECT    : SexpObject passed as a CObject
    -DRPY_DEBUG_GRDEV
    """
    user_options = _build_ext.user_options + \
        [
        #('r-autoconfig', None,
        #  "guess all configuration paths from " +\
        #      "the R executable found in the PATH " +\
        #      "(this overrides r-home)"),
        ('r-home=', None, 
         "full path for the R home to compile against " +\
             "(see r-autoconfig for an automatic configuration)"),
        ('r-home-lib=', None,
         "full path for the R shared lib/ directory" +\
             "(<r-home>/lib otherwise)"),
        ('r-home-modules=', None,
         "full path for the R shared modules/ directory" +\
             "(<r-home>/modules otherwise)")]

    boolean_options = _build_ext.boolean_options #+ \
        #['r-autoconfig', ]

    def initialize_options(self):
        _build_ext.initialize_options(self)
        self.r_autoconfig = None
        self.r_home = None
        self.r_home_lib = None
        self.r_home_modules = None

    def finalize_options(self):
        self.set_undefined_options('build',
                                   #('r_autoconfig', 'r_autoconfig'),
                                   ('r_home', 'r_home'))
        _build_ext.finalize_options(self) 
        if self.r_home is None:
            self.r_home = os.popen("R RHOME").readlines()
            if len(self.r_home) == 0:
                raise SystemExit("Error: Tried to guess R's HOME but no R command in the PATH.")

    #Twist if 'R RHOME' spits out a warning
            if self.r_home[0].startswith("WARNING"):
                self.r_home = self.r_home[1]
            else:
                self.r_home = self.r_home[0]
            #self.r_home = [self.r_home, ]

        if self.r_home is None:
            raise SystemExit("Error: --r-home not specified.")
        else:
            self.r_home = self.r_home.split(os.pathsep)

        rversions = []
        for r_home in self.r_home:
            r_home = r_home.strip()
        rversion = get_rversion(r_home)
        if cmp_version(rversion[:2], [2, 8]) == -1:
            raise SystemExit("Error: R >= 2.8 required.")
        rversions.append(rversion)

        config = RConfig()
        for about in ('--ldflags', '--cppflags', 
                      'LAPACK_LIBS', 'BLAS_LIBS'):
            config += get_rconfig(r_home, about)

        print(config.__repr__())

        self.include_dirs.extend(config._include_dirs)
        self.libraries.extend(config._libraries)
        self.library_dirs.extend(config._library_dirs)

        if self.r_home_modules is None:
            self.library_dirs.extend([os.path.join(r_home, 'modules'), ])
        else:
            self.library_dirs.extends([self.r_home_modules, ])

        #for e in self.extensions:
        #    self.extra_link_args.extra_link_args(config.extra_link_args)
        #    e.extra_compile_args.extend(extra_compile_args)

    def run(self):
        _build_ext.run(self)



def get_rversion(r_home):
    r_exec = os.path.join(r_home, 'bin', 'R')
    # Twist if Win32
    if sys.platform == "win32":
        rp = os.popen3('"'+r_exec+'" --version')[2]
    else:
        rp = os.popen('"'+r_exec+'" --version')
    rversion = rp.readline()
    #Twist if 'R RHOME' spits out a warning
    if rversion.startswith("WARNING"):
        rversion = rp.readline()
    m = re.match('^R version ([^ ]+) .+$', rversion)
    rversion = m.groups()[0]
    rversion = rversion.split('.')
    rversion[0] = int(rversion[0])
    rversion[1] = int(rversion[1])
    return rversion

def cmp_version(x, y):
    if (x[0] < y[0]):
        return -1
    if (x[0] > y[0]):
        return 1
    if (x[0] == y[0]):
        if len(x) == 1 or len(y) == 1:
            return 0
        return cmp_version(x[1:], y[1:])

class RConfig(object):
    _include_dirs = None
    _libraries = None
    _library_dirs = None 
    _extra_link_args = None
    _frameworks = None
    _framework_dirs = None
    def __init__(self,
                 include_dirs = tuple(), libraries = tuple(),
                 library_dirs = tuple(), extra_link_args = tuple(),
                 frameworks = tuple(),
                 framework_dirs = tuple()):
        for k in ('include_dirs', 'libraries', 
                  'library_dirs', 'extra_link_args'):
            v = locals()[k]
            if not isinstance(v, tuple):
                if isinstance(v, str):
                    v = [v, ]
            v = tuple(set(v))
            self.__dict__['_'+k] = v
        # frameworks are specific to OSX
        for k in ('framework_dirs', 'frameworks'):
            v = locals()[k]
            if not isinstance(v, tuple):
                if isinstance(v, str):
                    v = [v, ]
            v = tuple(set(v))
            self.__dict__['_'+k] = v
            self.__dict__['_'+'extra_link_args'] = tuple(set(v + self.__dict__['_'+'extra_link_args']))


    def __repr__(self):
        s = 'Configuration for R as a library:' + os.linesep
        s += os.linesep.join(
            ['  ' + x + ': ' + self.__dict__['_'+x].__repr__() \
                 for x in ('include_dirs', 'libraries',
                           'library_dirs', 'extra_link_args')])
        s += os.linesep + ' # OSX-specific (included in extra_link_args)' + os.linesep 
        s += os.linesep.join(
            ['  ' + x + ': ' + self.__dict__['_'+x].__repr__() \
                 for x in ('framework_dirs', 'frameworks')]
            )

        return s

    def __add__(self, config):
        assert isinstance(config, RConfig)
        res = RConfig(include_dirs = self._include_dirs + \
                          config._include_dirs,
                      libraries = self._libraries + config._libraries,
                      library_dirs = self._library_dirs + \
                          config._library_dirs,
                      extra_link_args = self._extra_link_args + \
                          config._extra_link_args)
        return res
    @staticmethod
    def from_string(string, allow_empty = False):
        possible_patterns = ('^-L(?P<library_dirs>[^ ]+)$',
                             '^-l(?P<libraries>[^ ]+)$',
                             '^-I(?P<include_dirs>[^ ]+)$',
                             '^(?P<framework_dirs>-F[^ ]+?)$',
                             '^(?P<frameworks>-framework [^ ]+)$')
        pp = [re.compile(x) for x in possible_patterns]
        # sanity check of what is returned into rconfig
        rconfig_m = None        
        span = (0, 0)
        rc = RConfig()
        for substring in re.split('(?<!-framework) ', string):
            ok = False
            for pattern in pp:
                rconfig_m = pattern.match(substring)
                if rconfig_m is not None:
                    rc += RConfig(**rconfig_m.groupdict())
                    span = rconfig_m.span()
                    ok = True
                    break
                elif rconfig_m is None:
                    if allow_empty and (rconfig == ''):
                        print(cmd + '\nreturned an empty string.\n')
                        rc += RConfig()
                        ok = True
                        break
                    else:
                        # if the configuration points to an existing library, 
                        # use it
                        if os.path.exists(string):
                            rc += RConfig(library = substring)
                            ok = True
                            break
            if not ok:
                raise ValueError('Invalid substring\n' + substring 
                                 + '\nin string\n' + string)
        return rc

def get_rconfig(r_home, about, allow_empty = False):
    r_exec = os.path.join(r_home, 'bin', 'R')
    cmd = '"'+r_exec+'" CMD config '+about
    rp = os.popen(cmd)
    rconfig = rp.readline()
    #Twist if 'R RHOME' spits out a warning
    if rconfig.startswith("WARNING"):
        rconfig = rp.readline()
    rconfig = rconfig.strip()
    rc = RConfig.from_string(rconfig)
    return rc


def getRinterface_ext():
    #r_libs = [os.path.join(RHOME, 'lib'), os.path.join(RHOME, 'modules')]
    r_libs = []
    extra_link_args = []

    #FIXME: crude way (will break in many cases)
    #check how to get how to have a configure step
    define_macros = []

    if sys.platform == 'win32':
        define_macros.append(('Win32', 1))
    else:
        define_macros.append(('R_INTERFACE_PTRS', 1))
        define_macros.append(('HAVE_POSIX_SIGJMP', 1))

    define_macros.append(('CSTACK_DEFNS', 1))
    define_macros.append(('RIF_HAS_RSIGHAND', 1))

    include_dirs = []

    rinterface_ext = Extension(
            name = pack_name + '.rinterface.rinterface',
            sources = [ \
            #os.path.join('rpy', 'rinterface', 'embeddedr.c'), 
            #os.path.join('rpy', 'rinterface', 'r_utils.c'),
            #os.path.join('rpy', 'rinterface', 'buffer.c'),
            #os.path.join('rpy', 'rinterface', 'sequence.c'),
            #os.path.join('rpy', 'rinterface', 'sexp.c'),
            os.path.join('rpy', 'rinterface', 'rinterface.c')
                       ],
            depends = [os.path.join('rpy', 'rinterface', 'embeddedr.h'), 
                       os.path.join('rpy', 'rinterface', 'r_utils.h'),
                       os.path.join('rpy', 'rinterface', 'buffer.h'),
                       os.path.join('rpy', 'rinterface', 'sequence.h'),
                       os.path.join('rpy', 'rinterface', 'sexp.h'),
                       os.path.join('rpy', 'rinterface', 'rpy_rinterface.h')
                       ],
            include_dirs = [os.path.join('rpy', 'rinterface'),] + include_dirs,
            libraries = ['R', ],
            library_dirs = r_libs,
            define_macros = define_macros,
            runtime_library_dirs = r_libs,
            #extra_compile_args=['-O0', '-g'],
            #extra_link_args = extra_link_args
            )

    rpy_device_ext = Extension(
        pack_name + '.rinterface.rpy_device',
            [
            os.path.join('rpy', 'rinterface', 'rpy_device.c'),
             ],
            include_dirs = include_dirs + 
                            [os.path.join('rpy', 'rinterface'), ],
            libraries = ['R', ],
            library_dirs = r_libs,
            define_macros = define_macros,
            runtime_library_dirs = r_libs,
            #extra_compile_args=['-O0', '-g'],
            extra_link_args = extra_link_args
        )

    return [rinterface_ext, rpy_device_ext]


rinterface_exts = []
ri_ext = getRinterface_ext()
rinterface_exts.append(ri_ext)

pack_dir = {pack_name: 'rpy'}

import distutils.command.install
for scheme in distutils.command.install.INSTALL_SCHEMES.values():
    scheme['data'] = scheme['purelib']

setup(
    #install_requires=['distribute'],
    cmdclass = {'build': build,
                'build_ext': build_ext},
    name = pack_name,
    version = pack_version,
    description = "Python interface to the R language",
    url = "http://rpy.sourceforge.net",
    license = "AGPLv3.0 (except rpy2.rinterface: LGPL)",
    author = "Laurent Gautier",
    author_email = "lgautier@gmail.com",
    ext_modules = rinterface_exts[0],
    package_dir = pack_dir,
    packages = [pack_name,
                pack_name + '.rlike',
                pack_name + '.rlike.tests',
                pack_name + '.rinterface',
                pack_name + '.rinterface.tests',
                pack_name + '.robjects',
                pack_name + '.robjects.tests',
                pack_name + '.robjects.lib',
                ],
    classifiers = ['Programming Language :: Python',
                   'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
                   'License :: OSI Approved :: GNU Affero General Public License v3',
                   'Intended Audience :: Developers',
                   'Intended Audience :: Science/Research',
                   'Development Status :: 5 - Production/Stable'
                   ],
    data_files = [(os.path.join('rpy2', 'images'), 
                   [os.path.join('doc', 'source', 'rpy2_logo.png')])]

    #[pack_name + '.rinterface_' + x for x in rinterface_rversions] + \
        #[pack_name + '.rinterface_' + x + '.tests' for x in rinterface_rversions]
    )

해결법

  1. ==============================

    1.내가 파티에 좀 늦었다는 것을 알고 있지만, 같은 문제가 있었고 Windows 7에서 conda를 통해 설치를 수행했습니다.

    내가 파티에 좀 늦었다는 것을 알고 있지만, 같은 문제가 있었고 Windows 7에서 conda를 통해 설치를 수행했습니다.

    conda install --channel https://conda.binstar.org/joshadel rpy2
    
  2. ==============================

    2.비슷한 문제가 r 2.12 및 Python 2.6 (rpy2 설명서에서 권장하는) rpy2 사용하려고했습니다.

    비슷한 문제가 r 2.12 및 Python 2.6 (rpy2 설명서에서 권장하는) rpy2 사용하려고했습니다.

    http://cran.r-project.org/bin/windows/base/R-2.12.1-win.exe의 Windows 바이너리는 rpy2가 예상하지 않는 디렉토리에 필요한 R.dll을 설치하는 것으로 보입니다.

    R \ R-2.12.1 \ bin \ i386의 모든 파일을 bin 디렉토리로 복사하고 환경 변수 R_HOME을 R \ R-2.12.1로 설정 한 다음 작동합니다.

  3. ==============================

    3.나는 다소 다른 설치 문제를 겪었으며 마침내 http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg02817.html에서 해결책을 찾았습니다.

    나는 다소 다른 설치 문제를 겪었으며 마침내 http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg02817.html에서 해결책을 찾았습니다.

    rpy2-2.0.8.win32-py2.6.msi (Windows 7 (64 비트), Python 2.6, R 2.14 (32 비트 및 64 비트 모두, RAndFriendsSetup2140V3.2-1-1.exe를 통해)를 통해 rpy2 2.0.8을 설치 한 후, ), 파이썬 콘솔 내에서 rpy2를 가져 오려고 시도했다면 예외가 발생했습니다.

    R.dll을 찾을 수 없습니다.

    rinterface / __ init__.py에 다음 행을 추가하여 작동하게했습니다.

    if os.path.exists(os.path.join(R_HOME, 'lib')):             ## ADDED ##
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'bin')
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'modules')
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'lib')
    else:                                   ## ADDED ##
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'bin', 'i386')     ## ADDED ##
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'modules', 'i386') ## ADDED ##
        os.environ['PATH'] += ';' + os.path.join(R_HOME, 'library')     ## ADDED ##
    
    # Load the R dll using the explicit path
    # First try the bin dir:
    Rlib = os.path.join(R_HOME, 'bin', 'R.dll')
    # Try bin/i386 subdirectory seen in R 2.12.0                ## ADDED ##
    if not os.path.exists(Rlib):                        ## ADDED ##
        Rlib = os.path.join(R_HOME, 'bin', 'i386', 'R.dll')         ## ADDED ##
    # Then the lib dir:
    if not os.path.exists(Rlib):
        Rlib = os.path.join(R_HOME, 'lib', 'R.dll')
    # Otherwise fail out!
    if not os.path.exists(Rlib):
        raise RuntimeError("Unable to locate R.dll within %s" % R_HOME)
    

    R.dll이 이동되었지만 __init__.py가 그에 따라 업데이트되지 않는 것으로 나타났습니다. 따라서 __init__.py 파일을 편집하는 것만으로도 올바르게 작동합니다.

    그런 다음 Taj G의 상황을 재현하려고 시도했습니다. "your_R_installation_dir \ bin \ i386"을 Windows 환경 변수 PATH에 추가 한 후 이전 오류는 사라졌지만 새로운 오류가 발생했습니다.

    ValueError : 문자열의 유효하지 않은 하위 문자열

    추가 조각을 설치해야하고 C / C ++ 컴파일러를 올바르게 구성해야합니다. 나는 여기서 포기했다. easy_install을 사용하여 소스에서 rpy2를 빌드하는 것은 Windows에서 매우 까다 롭고 현재 공식적으로 지원하지 않습니다.

    rpy2 2.0.8은 2.2.4에 비해 본격 버전은 아니지만 sourceforge에 표준 Windows 인스톨러가있는 최신 버전입니다. 지금은 쉬운 선택입니다.

  4. ==============================

    4.나도 RPy2에 문제가 있었고 실제로는 다른 솔루션을 시도해 본 며칠이나 며칠 지난 후에도 작동하지 못했습니다. 사람들이 당신에게 말하는 멋진 아이디어를 모두 시험해보고, 그 중 어떤 것이 효과가 있는지보고 싶습니다.

    나도 RPy2에 문제가 있었고 실제로는 다른 솔루션을 시도해 본 며칠이나 며칠 지난 후에도 작동하지 못했습니다. 사람들이 당신에게 말하는 멋진 아이디어를 모두 시험해보고, 그 중 어떤 것이 효과가 있는지보고 싶습니다.

    내가 그랬던 것처럼 실패한다면, 목적에 따라 다음과 같은 방법으로 해결 방법을 사용할 수 있습니다.

  5. ==============================

    5.나는 정확하게 같은 문제를 가지고 있었다. rpy2를 파이썬에서 win32 "WINBLOW :)"XP; 그러나 나는 이것을 일하게했다, 마침내!!

    나는 정확하게 같은 문제를 가지고 있었다. rpy2를 파이썬에서 win32 "WINBLOW :)"XP; 그러나 나는 이것을 일하게했다, 마침내!!

    방법은 다음과 같습니다.

    내 컴퓨터> 속성> 고급> 환경 변수>   변수 : "PATH", 추가 : C : \ Program Files \ R \ R-2.15.0 "값"

    희망이 도움이, 그리고이 작품은 당신에게 알려 주시기 바랍니다.

  6. ==============================

    6.rpy2가 Windows 7에서 소스 코드로 작업하게되었습니다. 그것이 나를 위해하지 않은 것처럼 그것은 당신을 위해 작동하지 않는 경우. Windows 7에서 rpy2 install을 참조하십시오.

    rpy2가 Windows 7에서 소스 코드로 작업하게되었습니다. 그것이 나를 위해하지 않은 것처럼 그것은 당신을 위해 작동하지 않는 경우. Windows 7에서 rpy2 install을 참조하십시오.

    희망이 도움이 !!

  7. from https://stackoverflow.com/questions/4924917/trouble-installing-rpy2-on-win7-r-2-12-python-2-5 by cc-by-sa and MIT license