0

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?

2
  • There is also a C version of xlsxwriter, called libxlsxwriter, that you can use directly in Swift via CocoaPod or via the Swift wrapper. Commented Dec 8, 2022 at 14:22
  • @jmcnamara, thank you! I'll definitely keep that in mind if I have to write something like that again. I just want to get this project integrated and done though. Commented Dec 8, 2022 at 16:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.