Skip to content

Commit b9798aa

Browse files
committed
[3.15] gh-162115: Add tooling to process site packages in an Apple Xcode project. (GH-162194)
Add tooling to process site packages in an Apple Xcode project. (cherry picked from commit 846acf1) Co-authored-by: Russell Keith-Magee <russell@keith-magee.com>
1 parent 23e1562 commit b9798aa

7 files changed

Lines changed: 74 additions & 106 deletions

File tree

‎Doc/using/ios.rst‎

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,21 @@ To add Python to an iOS Xcode project:
187187
adjusting paths as needed. Ensure that this folder is associated with your
188188
app target.
189189

190-
4. Select the app target by selecting the root node of your Xcode project, then
190+
4. Create folders to store your third-party dependencies (e.g., packages you've
191+
installed from PyPI). You'll need a separate dependencies folder for iOS
192+
devices and iOS simulators. In the following instructions, we'll assume
193+
you've used folders named ``app_packages.iphoneos`` and
194+
``app_packages.iphonesimulator``, located in the root of your project; you
195+
can use any other location by adjusting paths as needed. These folders
196+
*should not* be associated with the app target.
197+
198+
5. Select the app target by selecting the root node of your Xcode project, then
191199
the target name in the sidebar that appears.
192200

193-
5. In the "General" settings, under "Frameworks, Libraries and Embedded
201+
6. In the "General" settings, under "Frameworks, Libraries and Embedded
194202
Content", add ``Python.xcframework``, with "Embed & Sign" selected.
195203

196-
6. In the "Build Settings" tab, modify the following:
204+
7. In the "Build Settings" tab, modify the following:
197205

198206
- Build Options
199207

@@ -209,7 +217,7 @@ To add Python to an iOS Xcode project:
209217

210218
* Quoted Include In Framework Header: No
211219

212-
7. Add a build step that processes the Python standard library, and your own
220+
8. Add a build step that processes the Python standard library, and your own
213221
Python binary dependencies. In the "Build Phases" tab, add a new "Run
214222
Script" build step *before* the "Embed Frameworks" step, but *after* the
215223
"Copy Bundle Resources" step. Name the step "Process Python libraries",
@@ -221,11 +229,18 @@ To add Python to an iOS Xcode project:
221229
set -e
222230
source "$PROJECT_DIR/Python.xcframework/build/utils.sh"
223231
install_python Python.xcframework app
232+
if [ "$EFFECTIVE_PLATFORM_NAME" = "-iphonesimulator" ]; then
233+
APP_PACKAGES_DIR="$PROJECT_DIR/app_packages.iphonesimulator/"
234+
else
235+
APP_PACKAGES_DIR="$PROJECT_DIR/app_packages.iphoneos/"
236+
fi
237+
rsync -au --delete "$APP_PACKAGES_DIR" "$CODESIGNING_FOLDER_PATH/app_packages"
238+
install_site_packages Python.xcframework app_packages
224239
225240
If you have placed your XCframework somewhere other than the root of your
226241
project, modify the path to the first argument.
227242

228-
8. Add Objective C code to initialize and use a Python interpreter in embedded
243+
9. Add Objective C code to initialize and use a Python interpreter in embedded
229244
mode. You should ensure that:
230245

231246
* UTF-8 mode (:c:member:`PyPreConfig.utf8_mode`) is *enabled*;
@@ -234,36 +249,14 @@ To add Python to an iOS Xcode project:
234249
* Signal handlers (:c:member:`PyConfig.install_signal_handlers`) are *enabled*;
235250
* System logging (:c:member:`PyConfig.use_system_logger`) is *enabled*
236251
(optional, but strongly recommended; this is enabled by default);
237-
* :envvar:`PYTHONHOME` for the interpreter is configured to point at the
238-
``python`` subfolder of your app's bundle; and
239-
* The :envvar:`PYTHONPATH` for the interpreter includes:
240-
241-
- the ``python/lib/python3.X`` subfolder of your app's bundle,
242-
- the ``python/lib/python3.X/lib-dynload`` subfolder of your app's bundle, and
243-
- the ``app`` subfolder of your app's bundle
252+
* The interpreter's home direectory (:c:member:`PyConfig.home`) is configured
253+
to point at the ``python`` subfolder of your app's bundle; and
254+
* The interpreter's module search paths (:c:member:`PyConfig.home`) includes
255+
the ``app`` subfolder of your app's bundle.
244256

245257
Your app's bundle location can be determined using ``[[NSBundle mainBundle]
246258
resourcePath]``.
247259

248-
Steps 7 and 8 of these instructions assume that you have a single folder of
249-
pure Python application code, named ``app``. If you have third-party binary
250-
modules in your app, some additional steps will be required:
251-
252-
* You need to ensure that any folders containing third-party binaries are
253-
either associated with the app target, or are explicitly copied as part of
254-
step 7. Step 7 should also purge any binaries that are not appropriate for
255-
the platform a specific build is targeting (i.e., delete any device binaries
256-
if you're building an app targeting the simulator).
257-
258-
* If you're using a separate folder for third-party packages, ensure that
259-
folder is added to the end of the call to ``install_python`` in step 7, and
260-
as part of the :envvar:`PYTHONPATH` configuration in step 8.
261-
262-
* If any of the folders that contain third-party packages will contain ``.pth``
263-
files, you should add that folder as a *site directory* (using
264-
:meth:`site.addsitedir`), rather than adding to :envvar:`PYTHONPATH` or
265-
:attr:`sys.path` directly.
266-
267260
Testing a Python package
268261
------------------------
269262

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
The iOS build utility script now contains better support for integrating
2+
third-party code into a project's site-packages folder. The testbed has
3+
been modified to use this script, ensuring that sub-interpreters can find
4+
all installed third-party dependencies.

‎Platforms/Apple/testbed/Python.xcframework/build/utils.sh‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
# -----
1616
# set -e
1717
# source "$PROJECT_DIR/Python.xcframework/build/utils.sh"
18-
# install_python Python.xcframework app app_packages
18+
# install_python Python.xcframework app
19+
# install_site_packages Python.xcframework app_packages
1920
# -----
2021

2122
# Copy the standard library from the XCframework into the app bundle.
@@ -132,20 +133,39 @@ process_dylibs () {
132133
#
133134
# Accepts 1 or more arguments:
134135
# 1. The path, relative to the root of the Xcode project, where the Python
135-
# XCframework can be found. If the XCframework is in the root of the project,
136-
# 2+. The path of a package, relative to the root of the packaged app, that contains
137-
# library content that should be processed for binary libraries.
136+
# XCframework can be found.
137+
# 2+. The path of any package, relative to the root of the Xcode project, that contains
138+
# user-space Python code that should be processed for binary libraries.
138139
install_python() {
139140
PYTHON_XCFRAMEWORK_PATH=$1
140141
shift
141142

142143
install_stdlib "$PYTHON_XCFRAMEWORK_PATH"
143-
PYTHON_VER=$(ls -1 "$CODESIGNING_FOLDER_PATH/python/lib" | grep -E "^python3\.\d+$")
144-
echo "Install Python $PYTHON_VER standard library extension modules..."
145-
process_dylibs "$PYTHON_XCFRAMEWORK_PATH" python/lib/$PYTHON_VER/lib-dynload
144+
PYTHON_LIBDIR=$(ls -1 "$CODESIGNING_FOLDER_PATH/python/lib" | grep -E "^python3\.\d+$")
145+
146+
echo "Install Python $PYTHON_LIBDIR standard library extension modules..."
147+
process_dylibs "$PYTHON_XCFRAMEWORK_PATH" python/lib/$PYTHON_LIBDIR/lib-dynload
146148

147149
for package_path in "$@"; do
148150
echo "Installing $package_path extension modules ..."
149151
process_dylibs "$PYTHON_XCFRAMEWORK_PATH" "$package_path"
150152
done
151153
}
154+
155+
# The entry point for post-processing the site packages for a Python XCframework.
156+
#
157+
# Accepts 2 arguments:
158+
# 1. The path, relative to the root of the Xcode project, where the Python
159+
# XCframework can be found.
160+
# 2. The path, relative to the root of the Xcode project, that contains
161+
# the site-packages content for the app.
162+
install_site_packages() {
163+
PYTHON_XCFRAMEWORK_PATH=$1
164+
APP_PACKAGES_PATH=$2
165+
PYTHON_LIBDIR=$(ls -1 "$CODESIGNING_FOLDER_PATH/python/lib" | grep -E "^python3\.\d+[a-z]*$")
166+
167+
echo "Install Python $PYTHON_LIBDIR site-packages extension modules..."
168+
rm -rf "$CODESIGNING_FOLDER_PATH/python/lib/$PYTHON_LIBDIR/site-packages"
169+
mv "$CODESIGNING_FOLDER_PATH/$APP_PACKAGES_PATH" "$CODESIGNING_FOLDER_PATH/python/lib/$PYTHON_LIBDIR/site-packages"
170+
process_dylibs "$PYTHON_XCFRAMEWORK_PATH" python/lib/$PYTHON_LIBDIR/site-packages
171+
}

‎Platforms/Apple/testbed/TestbedTests/TestbedTests.m‎

Lines changed: 10 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,9 @@ @implementation TestbedTests
1111
- (void)testPython {
1212
const char **argv;
1313
int exit_code;
14-
int failed;
1514
PyStatus status;
1615
PyPreConfig preconfig;
1716
PyConfig config;
18-
PyObject *app_packages_path;
19-
PyObject *method_args;
20-
PyObject *result;
21-
PyObject *site_module;
22-
PyObject *site_addsitedir_attr;
23-
PyObject *sys_module;
24-
PyObject *sys_path_attr;
2517
NSArray *test_args;
2618
NSString *python_home;
2719
NSString *path;
@@ -115,73 +107,24 @@ - (void)testPython {
115107
return;
116108
}
117109

118-
NSLog(@"Initializing Python runtime...");
119-
status = Py_InitializeFromConfig(&config);
120-
if (PyStatus_Exception(status)) {
121-
XCTFail(@"Unable to initialize Python interpreter: %s", status.err_msg);
122-
PyConfig_Clear(&config);
123-
return;
124-
}
125-
126-
// Add app_packages as a site directory. This both adds to sys.path,
127-
// and ensures that any .pth files in that directory will be executed.
128-
site_module = PyImport_ImportModule("site");
129-
if (site_module == NULL) {
130-
XCTFail(@"Could not import site module");
131-
return;
132-
}
133-
134-
site_addsitedir_attr = PyObject_GetAttrString(site_module, "addsitedir");
135-
if (site_addsitedir_attr == NULL || !PyCallable_Check(site_addsitedir_attr)) {
136-
XCTFail(@"Could not access site.addsitedir");
137-
return;
138-
}
139-
140-
path = [NSString stringWithFormat:@"%@/app_packages", resourcePath, nil];
141-
NSLog(@"App packages path: %@", path);
142-
wtmp_str = Py_DecodeLocale([path UTF8String], NULL);
143-
app_packages_path = PyUnicode_FromWideChar(wtmp_str, wcslen(wtmp_str));
144-
if (app_packages_path == NULL) {
145-
XCTFail(@"Could not convert app_packages path to unicode");
146-
return;
147-
}
148-
PyMem_RawFree(wtmp_str);
149-
150-
method_args = Py_BuildValue("(O)", app_packages_path);
151-
if (method_args == NULL) {
152-
XCTFail(@"Could not create arguments for site.addsitedir");
153-
return;
154-
}
155-
156-
result = PyObject_CallObject(site_addsitedir_attr, method_args);
157-
if (result == NULL) {
158-
XCTFail(@"Could not add app_packages directory using site.addsitedir");
159-
return;
160-
}
161-
162-
// Add test code to sys.path
163-
sys_module = PyImport_ImportModule("sys");
164-
if (sys_module == NULL) {
165-
XCTFail(@"Could not import sys module");
166-
return;
167-
}
168-
169-
sys_path_attr = PyObject_GetAttrString(sys_module, "path");
170-
if (sys_path_attr == NULL) {
171-
XCTFail(@"Could not access sys.path");
172-
return;
173-
}
174-
175110
path = [NSString stringWithFormat:@"%@/app", resourcePath, nil];
176111
NSLog(@"App path: %@", path);
177112
wtmp_str = Py_DecodeLocale([path UTF8String], NULL);
178-
failed = PyList_Insert(sys_path_attr, 0, PyUnicode_FromString([path UTF8String]));
179-
if (failed) {
113+
status = PyWideStringList_Insert(&config.module_search_paths, 0, wtmp_str);
114+
if (PyStatus_Exception(status)) {
180115
XCTFail(@"Unable to add app to sys.path");
181116
return;
182117
}
183118
PyMem_RawFree(wtmp_str);
184119

120+
NSLog(@"Initializing Python runtime...");
121+
status = Py_InitializeFromConfig(&config);
122+
if (PyStatus_Exception(status)) {
123+
XCTFail(@"Unable to initialize Python interpreter: %s", status.err_msg);
124+
PyConfig_Clear(&config);
125+
return;
126+
}
127+
185128
// Ensure the working directory is the app folder.
186129
chdir([path UTF8String]);
187130

‎Platforms/Apple/testbed/__main__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ def clone_testbed(
171171
"__main__.py",
172172
"TestbedTests",
173173
"Testbed.lldbinit",
174+
"prepare_python_code.sh",
174175
f"{platform}Testbed",
175176
f"{platform}Testbed.xcodeproj",
176177
f"{platform}Testbed.xctestplan",

‎Platforms/Apple/testbed/iOSTestbed.xcodeproj/project.pbxproj‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
/* End PBXCopyFilesBuildPhase section */
5050

5151
/* Begin PBXFileReference section */
52+
60214C9030AD4273006FA640 /* prepare_python_code.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = prepare_python_code.sh; sourceTree = "<group>"; };
5253
607A66122B0EFA380010BFC8 /* iOSTestbed.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iOSTestbed.app; sourceTree = BUILT_PRODUCTS_DIR; };
5354
607A662D2B0EFA3A0010BFC8 /* iOSTestbedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iOSTestbedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5455
607A664A2B0EFB310010BFC8 /* Python.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = Python.xcframework; sourceTree = "<group>"; };
@@ -110,6 +111,7 @@
110111
children = (
111112
60FE0EFB2E56BB6D00524F87 /* iOSTestbed.xctestplan */,
112113
607A664A2B0EFB310010BFC8 /* Python.xcframework */,
114+
60214C9030AD4273006FA640 /* prepare_python_code.sh */,
113115
607A66142B0EFA380010BFC8 /* iOSTestbed */,
114116
607A66302B0EFA3A0010BFC8 /* TestbedTests */,
115117
607A66132B0EFA380010BFC8 /* Products */,
@@ -250,7 +252,7 @@
250252
);
251253
runOnlyForDeploymentPostprocessing = 0;
252254
shellPath = /bin/sh;
253-
shellScript = "set -e\nsource \"$PROJECT_DIR/Python.xcframework/build/utils.sh\"\ninstall_python Python.xcframework app app_packages\n";
255+
shellScript = "set -e\nsource \"$PROJECT_DIR/prepare_python_code.sh\"\n";
254256
showEnvVarsInLog = 0;
255257
};
256258
/* End PBXShellScriptBuildPhase section */
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/bin/sh
2+
set -e
3+
source "$PROJECT_DIR/Python.xcframework/build/utils.sh"
4+
install_python "Python.xcframework" app
5+
install_site_packages "Python.xcframework" app_packages

0 commit comments

Comments
 (0)