Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling a python Command-line tool with arguments, with PythonKit using Swift

I have been experimenting a bit with PythonKit and have some simple examples working. However I would now like to call a python script that takes some command line arguments and I can’t seem to get it working – it mostly just crashes.

This is the code I am using in swift – I am trying to get the version number of the script:

let sys = Python.import("sys")
sys.path.append(“/Path/To/Script/Directory/“)
var example = Python.import(“my_script”)

example.main("-v")

If I call the script like so: example.main() – without any arguments at all, the script prints out its arguments:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

optional arguments:
    -v, --version         show program's version number and exit
    -H, --help            Display this information
    etc.

But PythonKit then crashes in:

@discardableResult
    func dynamicallyCall(
        withArguments args: [PythonConvertible] = []) -> PythonObject {
        return try! throwing.dynamicallyCall(withArguments: args)
    }

The crash seems to be caused by a call to sys.exit(0) in the python script just after the argument list is printed, when there are no arguments. The script works normally if I use it in the terminal.

So, can someone tell me how to call a python script that expects arguments, from PythonKit?

Also, is there something that I could do to prevent a crash if there are no arguments?

>Solution :

I’m not familiar with swift but know that python getting arguments from sys.argv list

So how about try to add arguments directly into sys object:

let sys = Python.import("sys")
sys.path.append(“/Path/To/Script/Directory/“)
sys.argv.append("-v")
var example = Python.import(“my_script”)
example.main()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading