Skip to content

Instantly share code, notes, and snippets.

@frehulfd
Last active February 8, 2016 14:25
Show Gist options
  • Save frehulfd/72719cdea13535a5b0f6 to your computer and use it in GitHub Desktop.
Save frehulfd/72719cdea13535a5b0f6 to your computer and use it in GitHub Desktop.
A Swift "Shell Script" to convert the output of "speedtest-cli" to csv
#!/usr/bin/xcrun swift
// A script to take the results of "speedtest-cli" and convert it into csv data.
// This script requires "speedtest-cli" to be installed via `pip`. It will print
// out the results in csv format like the following: "Date,Time,Ping,Download,Upload"
//
// e.g.:
// 2/8/16,9:13:00 AM,24.456,55.72,24.03
// This script is intended to be run as a "shell script", i.e.:
// $> chmod +x speedtest.swift
// $> ./speedtest.swift
import Foundation
func exec(command: String) -> (output: String, exitStatus: Int) {
let tokens = command.componentsSeparatedByString(" ")
let launchPath = tokens[0]
let arguments = tokens.dropFirst(1)
let task = NSTask()
task.launchPath = launchPath
task.arguments = Array(arguments)
let stdout = NSPipe()
task.standardOutput = stdout
task.launch()
task.waitUntilExit()
let outData = stdout.fileHandleForReading.readDataToEndOfFile()
let outStr = String(data: outData, encoding: NSUTF8StringEncoding)!
return (outStr, Int(task.terminationStatus))
}
let result = exec("/usr/local/bin/speedtest --simple")
let results = result
.output
.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
.prefix(3)
.flatMap { string -> String? in
let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return components.count > 1 ? components[1] : nil
}
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
let dateString = dateFormatter.stringFromDate(date)
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle
let timeString = dateFormatter.stringFromDate(date)
let printables = [dateString, timeString] + results
print(printables.joinWithSeparator(","))
@frehulfd
Copy link
Author

frehulfd commented Feb 8, 2016

I use this with a cron job on my home server to query Speedtest every hour and log it to a CSV file in my Dropbox folder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment