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:
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?
CodePudding user response:
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()