您的位置:首页 > 编程语言 > Qt开发

如何在苹果系统(Mac OS X)上安装PyQt4

2012-06-07 14:18 537 查看

下面是我的安装情况:

我的系统是Mac OS X 10.6.3,64位的,
我的系统是Mac OS X 10.6.3,64位的,我在这里先将64位转为32位的操作系统,在命令行下输入:

defaults write com.apple.versioner.python Prefer-32-Bit -bool yes
,回车。


转化后,系统需要重新启动,重启后,你可以在这里看到。这是系统就是32位内核的。

http://hi.csdn.net/attachment/201102/15/0_1297760592ZGOX.gif

要安装pyqt的python版本是 2.6.1

安装PtQt4前你需准备:

Xcode (10.6.1 自带Xcode)
Qt - 我使用的是qt-mac-cocoa-opensource-4.6.2.dmg
SIP - 我使用的是sip-4.12.1.tar.gz
PyQt4 - 我使用的是PyQt-mac-gpl-snapshot-4.8.4.tar.gz

创建了一个pyqt文件夹在硬盘根目录下,并将sip-4.12.1.tar.gz和PyQt-mac-gpl-snapshot-4.8.4.tar.gz

放到其中并解压。

1。先安装qt,默认安装,这一步大部分人不会有问题,跳过。

2。接下来,打开终端(Terminal,在 Applications(应用程序)/Utilities(实用工具)/ 下),在终端输入:
export VERSIONER_PYTHON_PREFER_32_BIT=yes。


3.


使用"cd 路径"命令将当前目录设为sip-4.12.1,如: cd /pyqt/sip-4.12.1/, 然后进行配置(configure)【Re-build SIP in 32bit 】在终端中执行

python configure.py --arch i386

配置(configure)完成后就开始编译,在终端中执行
引用
make clean(清除以前的安装信息)
make

编译完成后就安装,在终端中执行
引用
sudo make install

在这个过程中没出现错误就是安装成功了

编译安装PyQt4,过程和上面的一样。 【Build PyQt4 in 32bit 】

在终端中使用"cd 路径"命令将当前目录设为PyQt-mac-gpl-snapshot-4.8.4,如

引用
cd /Users/schi/pyqt/PyQt-mac-gpl-snapshot-4.8.4

然后进行配置(configure),在终端中执行
引用
python configure.py --use-arch i386

配置时会遇到
引用
Determining the layout of your Qt installation...

This is the GPL version of PyQt 4.6 (licensed under the GNU General Public

License) for Python 2.6.2 on darwin.

Type '2' to view the GPL v2 license.

Type '3' to view the GPL v3 license.

Type 'yes' to accept the terms of the license.

Type 'no' to decline the terms of the license.

Do you accept the terms of the license?

输入yes,再按回车就行

配置(configure)完成后就开始编译,在终端中执行

引用
make clean
make

编译比较花时间,请耐心等待。

编译完成后就安装,在终端中执行

引用
sudo make install

在这个过程中没出现错误就是安装成功了

也可以在IDLE中导入PyQt4的模块,能成功导入就说明安装成功

Python代码



from PyQt4 import QtCore, QtGui

下面分析一下安装过程中可能遇到的问题:

1.问题如下

##############

ld: warning: in /Library/Frameworks/Python.framework/Python, missing required architecture x86_64 in file

Undefined symbols:

"_Py_Initialize", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyLong_AsVoidPtr", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyErr_Print", referenced from:

PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o

PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyString_FromString", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyType_IsSubtype", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyModule_GetDict", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyObject_CallObject", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyObject_CallFunctionObjArgs", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyList_Append", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_Py_IsInitialized", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyDict_Next", referenced from:

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyImport_ImportModule", referenced from:

PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o

PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o

"_PyObject_GetAttrString", referenced from:

PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o

ld: symbol(s) not found

collect2: ld returned 1 exit status

make[1]: *** [libpythonplugin.dylib] Error 1

make: *** [all] Error 2

这个问题的原因就是:qt是在32位mac上编译的,但pyqt默认是在64位机子上编译的,所以我们在编译的时候要制定编译环境:是i386 还是x86_64.

请参考如下的信息:

The problem is that the Qt library is 32bit while, by default, python builds PyQt4 in 64bit. That caused problem when it tried to link 64bit object files
with 32bit Qt library. To fix this issue, we need to force python to build PyQt4 in 32bit, and we also need to re-build SIP in 32bit mode. If you use the python version that comes with Mac OS (2.5 for Snow Leopard),
make sure that it runs in 32bit mode by issuing the command



2.个问题如下:

>>> from PyQt4 import QtGui

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ImportError: dlopen(/Library/Python/2.6/site-packages/PyQt4/QtGui.so, 2): Symbol not found: __ZN13QPyTextObject16staticMetaObjectE

Referenced from: /Library/Python/2.6/site-packages/PyQt4/QtGui.so

Expected in: flat namespace

in /Library/Python/2.6/site-packages/PyQt4/QtGui.so

这个问题是所有的包安装都没有问题但是当导入QtGui或其他包时,总报这个问题,这个问题的原因是,当前pyqt release的包本身带的一个bug,PyQt-mac-gpl-snapshot-4.8.3, 所以你下载下个要release的包就可以了。如我下的是:PyQt-mac-gpl-snapshot-4.8.4。

下面给大家介绍一下我写的自动安装这些程序的python源码:

#!/usr/bin/env python

"""

Automated installer for Python 2.6 (final)

This installer is able to handle any previous

versions of Python.

NOTE: This file *must* be copied to

//nssgsvr/tools/pyInstall_OSX when modified!

"""

import os

import sys

import re

import shutil

import platform

import tarfile

# Constants

PYTHON_PKGS = {"dmgFile" : "python-2.6.1-macosx2008-12-06.dmg",

"mpkgList": ["MacPython.mpkg"] }

#WXPYTHON_PKGS = {"dmgFile" : "wxPython2.8-osx-unicode-2.8.9.2-universal-py2.6.dmg",

# "mpkgList": ["wxPython2.8-osx-unicode-universal-py2.6.pkg"] }

#ANGELIA

XCODE_PKGS = {"dmgFile" : None, "mpkgList": ["Xcode.mpkg"]}

QT_PKGS = {"dmgFile" : "qt-mac-cocoa-opensource-4.6.2.dmg",

"mpkgList": ["Qt.mpkg"] }

THIRD_PARTY_INSTALL = ["sip-4.12.1", "PyQt-mac-gpl-snapshot-4.8.4","Pyro-3.9.1", "pyserial-2.4"]

# Environment constants

TCSH_ENV_FILE = '/etc/csh.login'

BASH_ENV_FILE = '/etc/profile'

SCRIPTS_ROOT_ENV = "TEST_SCRIPTS_ROOT"

TARGET_VER = "2.6"

IS_POSIX = (os.name == 'posix')

IS_MAC = (sys.version.find('Apple') != -1)

IS_OSX = (IS_MAC and IS_POSIX)

IS_OSX_LEOPARD = (IS_OSX and platform.mac_ver()[0].startswith('10.5'))

IS_OSX_SNOWLEOPARD = (IS_OSX and platform.mac_ver()[0].startswith('10.6'))

# NSSGSVR Constants

MOUNT_POINT = "/Volumes/Test"

HOSTSERVER = "NSSGSVR.global.avidww.com" # Server that contains SQA scripts

SHARE = "TEST" # NSSGSVR share that contains the Python scripts directory

USER = "qatest"

PASSWD = "Cmqat/$/$/$" # slashes needed to escape special character '$'

##################################################################################

class InstallerError(Exception):

""" Installer Exception class """

def __init__(self, description):

self.desc = description

def __str__(self):

return self.desc

class PkgInstaller:

""" Installer class for pkg files."""

def __init__(self, packageName, mpkgList, dmgFile = None ):

"""

packageName (str) Name of "package" to be installed

dmgFile (str) Path to dmg file to mount

mpkgList (list) List of mpkg files to launch when dmg file is mounted

"""

self.dmgFile = dmgFile

self.packageName = packageName

self.mpkgList = mpkgList

self.mountpoint = os.path.join(os.getcwd(), self.packageName)

self.removeMountPoint = False

if not type(self.mpkgList) == list:

raise InstallerError("Expected list for parameter mpkgList received %s" % /

type(self.mpkgList))

# Mountroot must exist for hdiutil to succeed.

if not os.path.exists(self.mountpoint):

print "Creating mountroot %s" % (self.mountpoint)

os.makedirs(self.mountpoint)

self.removeMountPoint = True

def _cleanup(self):

"""

## Performs cleanup

"""

unmount_cmd = "hdiutil unmount %s" % (self.mountpoint)

if self.dmgFile:

print "Unmounting %s" % (self.mountpoint)

ret = os.system(unmount_cmd)

if ret:

raise InstallerError("hdiutil unmount of %s failed: errno %d" % /

(self.mountpoint, ret))

if self.removeMountPoint:

print "Removing directory %s" % (self.mountpoint)

os.rmdir(self.mountpoint)

def _mount_dmg(self):

""" Mounts the dmg file. """

hdiutil_mount = "hdiutil mount %s -mountpoint %s" % (self.dmgFile,

self.mountpoint)

if os.path.exists(self.dmgFile):

print "Mounting %s" % (self.dmgFile)

ret = os.system(hdiutil_mount)

if ret:

raise InstallerError("hdiutil mount of %s failed: errno %d" % (self.dmgFile, ret))

else:

raise InstallerError("DMG file %s does not exist" % (self.dmgFile))

def _launch_pkgs(self):

""" Launches the pkg installers. """

for install_file in self.mpkgList:

if install_file.endswith('pkg'):

install_path = os.path.join(self.mountpoint, install_file)

if not os.path.exists(install_path):

raise InstallerError("File %s does not exist" % (install_path))

# 'installer' is Apple's package installer tool.

# -pkg specifies the package to be installed

# -target specifies the destination install volume

# -allow allows the installer to automatically upgrade any previous packages

# see 'man installer' for more details.

cmd = 'installer -pkg "%s" -target / -verbose -allow' % (install_path)

ret = os.system(cmd)

if ret:

msg = "Package %s failed to install: err %d" % (install_file, ret)

raise InstallerError(msg)

else:

raise InstallerError("File %s is not a valid package file" % install_file)

def install(self):

""" Main installer method. """

print "Installing package %s" % (self.packageName)

if self.dmgFile:

self._mount_dmg()

self._launch_pkgs()

self._cleanup()

print "Finished installing package %s" % (self.packageName)

def set_all_test_scripts_root(path):

"""

## Sets TEST_SCRIPTS_ROOT to <path> for

## both Bash and Tcsh shells if needed.

"""

bash_line = 'export TEST_SCRIPTS_ROOT="%s"' % (path)

tcsh_line = 'setenv TEST_SCRIPTS_ROOT "%s"' % (path)

scripts_root_bash = is_export_line_present(BASH_ENV_FILE, bash_line)

scripts_root_tcsh = is_export_line_present(TCSH_ENV_FILE, tcsh_line)

if not scripts_root_bash: _set_export_line(BASH_ENV_FILE, bash_line)

if not scripts_root_tcsh: _set_export_line(TCSH_ENV_FILE, tcsh_line)

def set_all_pythonpaths(path):

"""

## Sets PYTHONPATH to <path> for both

## Bash and Tcsh shells if needed.

"""

bash_line = 'export PYTHONPATH="%s"' % (path)

tcsh_line = 'setenv PYTHONPATH "%s"' % (path)

bash_set = is_export_line_present(BASH_ENV_FILE, bash_line)

tcsh_set = is_export_line_present(TCSH_ENV_FILE, tcsh_line)

if not bash_set: _set_export_line(BASH_ENV_FILE, bash_line)

if not tcsh_set: _set_export_line(TCSH_ENV_FILE, tcsh_line)

def _set_export_line(filepath, export_line):

"""

## Exports PYTHONPATH via global environment file

"""

try:

fd = open(filepath, 'a')

print "Adding line %s to file %s" % (export_line, filepath)

fd.write('/n' + export_line + '/n')

fd.close()

except IOError, e:

if (e.errno == 13):

print "Unable to set PYTHONPATH on file %s: Permission denied" % (filepath)

raise

def is_export_line_present(filepath, export_line):

"""

## Checks to see if <export_line> is present

## in file <filepath>.

"""

is_set = False

path_regex = re.compile("^%s$" % (export_line))

try:

fd = open(filepath, 'r')

except:

print "Unable to open %s for reading" % (filepath)

raise

lines = fd.readlines()

fd.close()

for line in lines:

if path_regex.match(line.strip('/n')):

is_set = True

break

return is_set

def mount_nssgsvr():

"""

## Mounts NSSGSVR

"""

mount_cmd = 'mount_smbfs '

mount_cmd += '//%s:%s@%s/%s %s' % (USER, PASSWD, HOSTSERVER, SHARE, MOUNT_POINT)

if not os.path.ismount(MOUNT_POINT):

if not os.path.exists(MOUNT_POINT):

os.mkdir(MOUNT_POINT)

mount_retval = os.system(mount_cmd)

if mount_retval:

raise InstallerError("Unable to mount %s" % (HOSTSERVER))

def get_python_version():

"""

## Returns the current version of Python

"""

return sys.version.split()[0]

def strvercmp(ver1, ver2):

"""

## Compares two version strings.

##

## Returns -1 if ver1 < ver2

## Returns 0 if ver1 == ver2

## Returns 1 if ver1 > ver2

"""

ver1 = ver1.strip()

ver2 = ver2.strip()

return cmp([int(num) for num in ver1.split('.')],

[int(num) for num in ver2.split('.')])

########################################################################################

## Main routine

def main(basePath):

"""

## Main routine.

"""

current_python_version = get_python_version()

# If the machine is not Leopard and attempting

# to install Python 2.5 over a later version of Python.

if not IS_OSX_SNOWLEOPARD:

if strvercmp(current_python_version, TARGET_VER) >= 0:

print "Attempting to install the same or an older version of Python"

print "Current version %s" % (current_python_version)

print "Attemping to install %s" % (TARGET_VER)

sys.exit(1)

else:

# set Snow Leopard to use only 32 bit

profile_handle = open("/etc/profile", 'a')

profile_handle.write("/nexport VERSIONER_PYTHON_PREFER_32_BIT=yes/n")

profile_handle.close()

# Change to directory containing installer script

if basePath: os.chdir(basePath)

# If the Scripts root install path environment variable already

# exists, use that as the default path. Otherwise use /python_scripts

if SCRIPTS_ROOT_ENV in os.environ.keys():

SCRIPTS_ROOT_DEFAULT = os.environ[SCRIPTS_ROOT_ENV]

else:

SCRIPTS_ROOT_DEFAULT = "/python_scripts"

print "NOTE: You *must* be connected to the network to complete this installation"

inpath = raw_input("Enter script install path (DEFAULT: '%s'): " % (SCRIPTS_ROOT_DEFAULT))

if inpath != "":

SCRIPTS_ROOT = inpath

else:

SCRIPTS_ROOT = SCRIPTS_ROOT_DEFAULT

# Only install the Python packages if we're not Snow Leopard.

# Python 2.6.1 and wxPython are installed by default in Snow Leopard.

if IS_OSX_SNOWLEOPARD:

# Need to make sure /etc/profile is readable and writable

# only by this user (root). Leopard by default

# makes /etc/profile just read-only by root.

assert(os.path.exists(BASH_ENV_FILE))

os.chmod(BASH_ENV_FILE, 0644)

else:

PYTHON = PkgInstaller("Python", PYTHON_PKGS['dmgFile'], PYTHON_PKGS['mpkgList'])

PYTHON.install()

#WXPYTHON = PkgInstaller("wxPython", WXPYTHON_PKGS['dmgFile'], WXPYTHON_PKGS['mpkgList'])

#WXPYTHON.install()

# Make sure python/pythonw symbolic links in /usr/bin

# points to the version located in /usr/local/bin because

# that binary will be from the Framework we installed above

python_symlink_src = '/usr/local/bin/python'

python_link = '/usr/bin/python'

if os.path.exists(python_link):

os.rename(python_link, python_link + '.old')

os.symlink(python_symlink_src, python_link)

pythonw_symlink_src = '/usr/local/bin/pythonw'

pythonw_link = '/usr/bin/pythonw'

if os.path.exists(pythonw_link):

os.rename(pythonw_link, pythonw_link + '.old')

os.symlink(pythonw_symlink_src, pythonw_link)

idle_link = '/usr/bin/idle'

# Add symlink for idle

if not os.path.exists(idle_link):

idle_symlink_src = '/Library/Frameworks/Python.framework/Versions/Current/bin/idle'

os.symlink(idle_symlink_src, idle_link)

# Set PYTHONPATH and TEST_SCRIPTS_ROOT if not set.

set_all_pythonpaths(SCRIPTS_ROOT)

set_all_test_scripts_root(SCRIPTS_ROOT)

#install necessary software

QT = PkgInstaller("Qt", QT_PKGS['mpkgList'], QT_PKGS['dmgFile'])

QT.install()

XCODE = PkgInstaller("xcode", XCODE_PKGS['mpkgList'])

XCODE.install()

# Install third party modules

for module in THIRD_PARTY_INSTALL:

install_dir = os.path.join(basePath, module)

if os.path.exists(install_dir):

os.chdir(install_dir)

if module in ['sip-4.12.1', 'PyQt-mac-gpl-snapshot-4.8.4']:

if module == 'sip-4.12.1' :

os.system('python configure.py --arch i386')

elif module == 'PyQt-mac-gpl-snapshot-4.8.4':

os.system('python configure.py --use-arch i386')

os.system('make clean')

os.system('make')

os.system('make install')

else:

print "/n#### INSTALL %s ####" % module

os.system('python setup.py install')

os.chdir('..')

else:

raise EnvironmentError("%s install directory not found!" % install_dir)

# Mount NSSGSVR to get update.py

mount_nssgsvr()

# Install and run update.py

if not os.path.exists(SCRIPTS_ROOT):

os.makedirs(SCRIPTS_ROOT)

update_path = os.path.join(SCRIPTS_ROOT, "update.py")

if os.path.exists(update_path):

os.remove(update_path)

print "Installing and running %s" % (update_path)

remote_update_path = os.path.join(MOUNT_POINT, 'sqatools', 'ISIS_Main','python_scripts_26', 'testware', 'py', 'update.py')

shutil.copy2(remote_update_path, SCRIPTS_ROOT)

os.chdir(SCRIPTS_ROOT)

os.path.exists("update.py")

os.system("python update.py -d%s -t " % SCRIPTS_ROOT)

# Change permissions for SCRIPTS_ROOT directory (since

# the script was run as root).

if os.path.exists(SCRIPTS_ROOT):

os.system("chown -R Administrator %s" % SCRIPTS_ROOT)

os.system("chmod -R og+rwx %s" % SCRIPTS_ROOT)

# Also change permissions for SCRIPTS_ROOT.old directory because

# of any backups made during the update executed above

scripts_root_old = SCRIPTS_ROOT + '.old'

if os.path.exists(scripts_root_old):

os.system("chown -R Administrator %s" % scripts_root_old)

os.system("chmod -R og+rwx %s" % scripts_root_old)

raw_input("Please quit and relaunch the Terminal application for the changes to take effect.")

if __name__ == "__main__":

if os.name != 'posix':

raise EnvironmentError("Invalid operating system")

if os.getuid() != 0:

print "Current user: /"%s/"" % (os.getlogin())

raise EnvironmentError("Script must be run as root")

base_path = os.path.dirname(sys.argv[0])

main(base_path)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐