How can I use XlsxWriter or other external libraries with PythonKit?

262 views Asked by At

I've been trying to use my XlsxWriter based python script in my swift app with PythonKit.

At first I tried installing XlsxWriter by running:

pip3 install XlsxWriter

It installed with no errors and the code runs fine in PyCharm when I import the library into the project. This however is broken in Swift.

My swift is:

import Foundation
import PythonKit


let dirPath = "/Users/johnson/Desktop/"

func runPythonCode(){
    let sys = Python.import("sys")
    sys.path.append(dirPath)
    let example = Python.import("sample")
    let response = example.hello()
    print(response)
}

runPythonCode()

My python is:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Heyeyeye')

workbook.close()

Xcode returns the following error when I try to run:

PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter

2022-12-08 11:09:52.812915+0200 Python-Test[21898:534512] PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter

Partial solution:

Running:

pip install XlsxWriter 

instead of:

pip3 install XlsxWriter

fixes this within Xcode.

Remaining issue:

When I export my executable via:

Xcode>Product>Archive>Distribute Content>Built Products

The executable runs the swift code fine, manages to import the python file but returns the following error:

PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'

The code runs fine within Xcode, no problems with xlsxwriter, but the standalone executable running the same python script fails. What could be causing this?

0

There are 0 answers