@@ -15,6 +15,11 @@ - (void)testPython {
15
15
PyStatus status;
16
16
PyPreConfig preconfig;
17
17
PyConfig config;
18
+ PyObject *app_packages_path;
19
+ PyObject *method_args;
20
+ PyObject *result;
21
+ PyObject *site_module;
22
+ PyObject *site_addsitedir_attr;
18
23
PyObject *sys_module;
19
24
PyObject *sys_path_attr;
20
25
NSArray *test_args;
@@ -111,29 +116,55 @@ - (void)testPython {
111
116
return ;
112
117
}
113
118
114
- sys_module = PyImport_ImportModule (" sys" );
115
- if (sys_module == NULL ) {
116
- XCTFail (@" Could not import sys module" );
119
+ // Add app_packages as a site directory. This both adds to sys.path,
120
+ // and ensures that any .pth files in that directory will be executed.
121
+ site_module = PyImport_ImportModule (" site" );
122
+ if (site_module == NULL ) {
123
+ XCTFail (@" Could not import site module" );
117
124
return ;
118
125
}
119
126
120
- sys_path_attr = PyObject_GetAttrString (sys_module , " path " );
121
- if (sys_path_attr == NULL ) {
122
- XCTFail (@" Could not access sys.path " );
127
+ site_addsitedir_attr = PyObject_GetAttrString (site_module , " addsitedir " );
128
+ if (site_addsitedir_attr == NULL || ! PyCallable_Check (site_addsitedir_attr) ) {
129
+ XCTFail (@" Could not access site.addsitedir " );
123
130
return ;
124
131
}
125
132
126
- // Add the app packages path
127
133
path = [NSString stringWithFormat: @" %@ /app_packages" , resourcePath, nil ];
128
134
NSLog (@" App packages path: %@ " , path);
129
135
wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
130
- failed = PyList_Insert (sys_path_attr, 0 , PyUnicode_FromString ([path UTF8String ] ));
131
- if (failed ) {
132
- XCTFail (@" Unable to add app packages to sys.path " );
136
+ app_packages_path = PyUnicode_FromWideChar (wtmp_str, wcslen (wtmp_str ));
137
+ if (app_packages_path == NULL ) {
138
+ XCTFail (@" Could not convert app_packages path to unicode " );
133
139
return ;
134
140
}
135
141
PyMem_RawFree (wtmp_str);
136
142
143
+ method_args = Py_BuildValue (" (O)" , app_packages_path);
144
+ if (method_args == NULL ) {
145
+ XCTFail (@" Could not create arguments for site.addsitedir" );
146
+ return ;
147
+ }
148
+
149
+ result = PyObject_CallObject (site_addsitedir_attr, method_args);
150
+ if (result == NULL ) {
151
+ XCTFail (@" Could not add app_packages directory using site.addsitedir" );
152
+ return ;
153
+ }
154
+
155
+ // Add test code to sys.path
156
+ sys_module = PyImport_ImportModule (" sys" );
157
+ if (sys_module == NULL ) {
158
+ XCTFail (@" Could not import sys module" );
159
+ return ;
160
+ }
161
+
162
+ sys_path_attr = PyObject_GetAttrString (sys_module, " path" );
163
+ if (sys_path_attr == NULL ) {
164
+ XCTFail (@" Could not access sys.path" );
165
+ return ;
166
+ }
167
+
137
168
path = [NSString stringWithFormat: @" %@ /app" , resourcePath, nil ];
138
169
NSLog (@" App path: %@ " , path);
139
170
wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
0 commit comments