Colabtools: Can't run shell script with when using colab with swift

Created on 14 Apr 2020  路  3Comments  路  Source: googlecolab/colabtools

Bug report for Colab: http://colab.research.google.com/.

For questions about colab usage, please use stackoverflow.

  • Describe the current behavior:
    Can't run shell script with when using colab with swift.
    When trying to run in simple shell commands like !ls, the result is not correct. It seems to just parse it as swift code.

  • Describe the expected behavior:
    When running !ls in a python notebook the result is sample_data.
    Expected behavior is that it runs the shell command.

  • The web browser you are using (Chrome, Firefox, Safari, etc.):
    Chrome

  • Link to self-contained notebook that reproduces this issue
    (click the Share button, then Get Shareable Link):
    https://colab.research.google.com/drive/1BXZN3tSQ2SGXknuaiKBRSjOH0IS6r0bQ

triaged

All 3 comments

This isn't a colab-specific question, it's really a swift question.

/cc @marcrasi for suggestions on where to direct.

https://github.com/google/swift-jupyter/issues is a good place to ask questions about Swift running in Colab. I can answer this question here.

Indeed, there is no ! handling in the Swift kernel. You need to use Swift to run shell commands. Here is one way to do that:

import Foundation
public extension String {
    @discardableResult
    func shell(_ args: String...) -> String
    {
        let (task,pipe) = (Process(),Pipe())
        task.executableURL = URL(fileURLWithPath: self)
        (task.arguments,task.standardOutput) = (args,pipe)
        do    { try task.run() }
        catch { print("Unexpected error: \(error).") }

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: data, encoding: String.Encoding.utf8) ?? ""
    }
}

print("/bin/ls".shell("-lh"))

This uses shell command through Python

import Python
let shell = Python.import("subprocess").getoutput
prefix func ! (_ command: String) { print(shell(command)) }

Now you can call just

!"ls -al"
Was this page helpful?
0 / 5 - 0 ratings