Swift Throws Python Errors from Terminal

swift throws python errors from terminal

I get the same error, because the swift REPL uses the python interpreter which homebrew installed at /usr/local/bin/python.

To avoid this you can

export PATH=/usr/bin:$PATH
swift

or

PATH=/usr/bin:$PATH swift

Swift REPL throws python error?

I changed the active python version (previously python 2.7 installed via macports) and it worked:

sudo port select python python33

UnicodeEncodeError: 'charmap' codec can't encode characters

I fixed it by adding .encode("utf-8") to soup.

That means that print(soup) becomes print(soup.encode("utf-8")).

Start python file in Swift

On your terminal type

which python3

this will return the path that is accessed when you run python3 from the command line

I can't use Python module in Swift

A year later, I got a solution.
The name of module was wrong.

import PythonKit
let np = Python.import("numpy")

I should have installed on this way and implemented this way exactly.

Thanks regards!

Xcode: 11.3.1

Swift: 4.2

Toolchain: Swift for TensorFlow 0.8 Release

String.endIndex incrementing error

There are two problems:

  • fieldName.endIndex is the "one past the end" position of the string,
    it has no successor.
  • You must not use the index of one string as the subscript for
    a different string. That may work in some cases, but can
    crash with a runtime exception if the strings contain
    characters outside of the "basic multilingual plane" (Emojis, flags, ...).

A working variant would be (Swift 2.2):

let fieldName = "VERSION:"
let versionField = "VERSION:4.1"

if versionField.hasPrefix(fieldName) {
let version = versionField.substringFromIndex(
versionField.startIndex.advancedBy(fieldName.characters.count))
print(version) // 4.1
} else {
print("No version found")
}

or alternatively:

if let range = versionField.rangeOfString(fieldName)
where range.startIndex == versionField.startIndex {
let version = versionField.substringFromIndex(range.endIndex)
print(version) // 4.1
} else {
print("No version found")
}

You can remove the constraint

where range.startIndex == versionField.startIndex

if the field should be found anywhere in the string.

Swift 3:

if versionField.hasPrefix(fieldName) {
let version = versionField.substring(
from: versionField.index(versionField.startIndex, offsetBy: fieldName.characters.count))
print(version) // 4.1
} else {
print("No version found")
}

or alternatively,

if let range = versionField.range(of: fieldName),
range.lowerBound == versionField.startIndex {
let version = versionField.substring(from: range.upperBound)
print(version) // 4.1
} else {
print("No version found")
}


Related Topics



Leave a reply



Submit