本文整理汇总了Scala中scala.sys.process.Process类的典型用法代码示例。如果您正苦于以下问题:Scala Process类的具体用法?Scala Process怎么用?Scala Process使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Process类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SysPropertiesTest
//设置package包名称以及导入依赖的类
package com.bob.scalatour.sys
import org.scalatest.FunSuite
import scala.sys.SystemProperties
import scala.sys.process.Process
class SysPropertiesTest extends FunSuite {
test("read system properties") {
val properties = new SystemProperties
assert(properties.contains("java.runtime.name"))
properties += ("objekt" -> "werks")
assert(properties.contains("objekt"))
properties -= "objekt"
assert(properties.getOrElse("objekt", "empty") == "empty")
}
test("using shell command") {
val file = Process("ls").lineStream.find(f => f == "build.sbt")
assert(file.getOrElse("empty") == "build.sbt")
val line = Process("find build.sbt").lineStream.headOption
assert(line.getOrElse("empty") == "build.sbt")
val lines = Process("cat .gitignore").lineStream.mkString.split("\\W+").groupBy(l => l).mapValues(l => l.length)
assert(lines.values.max == 3)
}
}
示例2: LoggingComponentTest
//设置package包名称以及导入依赖的类
package com.meetup.logging
import java.io.File
import org.scalatest.{FunSpec, Matchers}
import scala.sys.process.{Process, ProcessLogger}
class LoggingComponentTest extends FunSpec with Matchers {
val baseDir = new File("src/component/sbt")
var appJar = new File("target/scala-2.11/component-test.jar")
it("should work when used in runtime") {
val assemble = Process(Seq("sbt", "assembly", "run"), baseDir).!!.trim
println(assemble)
val proc = Process(Seq("java", "-jar", appJar.toString), baseDir)
val (out, err) = (new StringBuffer(), new StringBuffer())
val logger = ProcessLogger(
out.append(_),
err.append(_)
)
proc.!(logger)
out.toString should include("TestApp info")
err.toString should include("TestApp error")
}
}
示例3: GenerateFixtures
//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.initializers
import com.google.inject.{Inject, Singleton}
import org.birdfeed.chirp.database.SchemaTables
import org.birdfeed.chirp.database.models._
import play.api.{Environment, Logger}
import play.api.inject.DefaultApplicationLifecycle
import scala.sys.process.Process
import scala.util.Random
import com.github.t3hnar.bcrypt._
@Singleton
class GenerateFixtures @Inject()(lifecycle: DefaultApplicationLifecycle, env: Environment) {
SchemaTables.initialize
// Create Users
val admin = User("Test Admin", "[email protected]", "foobar123".bcrypt, 1).create
val researcher = User("Test Researcher", "[email protected]", "barbaz123".bcrypt, 2).create
val participant = User("Test Participant", "[email protected]", "quux456".bcrypt, 3).create
// Create some samples
val samples = 1 to 50 map { n =>
Sample(s"Sound Bite $n", researcher.id, "https://not.a.real.s3.url").create
}
// Create some experiments
1 to 10 foreach { n =>
val e = Experiment(s"Experiment $n", researcher.id).create
e.samples := Random.shuffle(samples).take(Random.nextInt(50))
}
// Generate an API key
Logger.debug(s"Fixture generation complete! Use this API key: ${ApiKey(true).create.key}")
SchemaTables.cleanup
// TODO: This is not graceful at all
lifecycle.stop
Process("kill `cat target/universal/stage/RUNNING_PID`")
}
示例4: TempestDBServerClientSpec
//设置package包名称以及导入依赖的类
package co.teapot.tempest.server
import java.io.File
import co.teapot.tempest.TempestDBService
import co.teapot.tempest.util.{ConfigLoader, LogUtil}
import co.teapot.thriftbase.TeapotThriftLauncher
import org.apache.thrift.TProcessor
import org.apache.thrift.server.TThreadPoolServer
import org.apache.thrift.transport.TServerSocket
import org.scalatest.{Matchers, FlatSpec}
import scala.concurrent.Future
import scala.sys.process.Process
import scala.concurrent.ExecutionContext.Implicits.global
class TempestDBServerClientSpec extends FlatSpec with Matchers with H2DatabaseBasedTest with SyntheticDatabaseData {
"A thrift client " should "correctly connect and use the scala endpoint " in {
// Regenerate the ruby and python packages based on the current source code
Process("src/main/bash/generate_thrift.sh").!
LogUtil.configureLog4j()
val processor = TempestDBTestServer.getProcessor("src/test/resources/config/tempest.yaml")
val serverTransport = new TServerSocket(10011)
val serverArgs = new TThreadPoolServer.Args(serverTransport).processor(processor)
val server = new TThreadPoolServer(serverArgs)
println("starting server at port " + 10011)
// If you want the server to serve indefinitely, so you can run ad-hoc client commands, uncomment this line:
// server.serve()
// Start the server on a new thread
Future[Unit] {
server.serve()
}
while (!server.isServing) {
Thread.sleep(10)
}
// This notation forwards the process output to stdout
val ret = Process("ruby -Iruby-package/lib src/test/ruby/tempest_test.rb").!
ret shouldEqual 0
val pythonResult = Process(
"src/test/python/tempest_test.py",
cwd = new File("."),
extraEnv = ("PYTHONPATH", "python-package")).!
pythonResult shouldEqual 0
server.stop()
}
}
示例5: Main
//设置package包名称以及导入依赖的类
package csw.services.tracklocation
import csw.services.BuildInfo
import csw.services.location.commons.{ClusterAwareSettings, ClusterSettings}
import csw.services.logging.scaladsl.LoggingSystemFactory
import csw.services.tracklocation.commons.LocationAgentLogger
import csw.services.tracklocation.models.Command
import csw.services.tracklocation.utils.ArgsParser
import scala.sys.process.Process
class Main(clusterSettings: ClusterSettings, startLogging: Boolean = false) extends LocationAgentLogger.Simple {
def start(args: Array[String]): Option[Process] =
ArgsParser.parse(args).map { options =>
val actorSystem = clusterSettings.system
if (startLogging)
LoggingSystemFactory.start(BuildInfo.name, BuildInfo.version, clusterSettings.hostname, actorSystem)
val command = Command.parse(options)
log.info(s"commandText: ${command.commandText}, command: ${command.toString}")
val trackLocation = new TrackLocation(options.names, command, actorSystem)
trackLocation.run()
}
}
object Main extends App with LocationAgentLogger.Simple {
if (ClusterAwareSettings.seedNodes.isEmpty) {
println(
"clusterSeeds setting is not specified either as env variable or system property. Please check online documentation for this set-up."
)
} else {
new Main(ClusterAwareSettings, startLogging = true).start(args)
}
}
示例6: SbtTestRunner
//设置package包名称以及导入依赖的类
package service.sbt
import java.nio.charset.StandardCharsets
import java.nio.file._
import java.nio.file.attribute.BasicFileAttributes
import scala.sys.process.{Process, ProcessLogger}
import scala.util.Try
object SbtTestRunner {
def createProjectAndTest(solution: String, appAbsolutePath: String): String = {
import scala.collection.JavaConversions._
Try {
val buildSbt = List(
"""lazy val root = (project in file("."))""",
""" .settings(""",
""" scalaVersion := "2.11.7",""",
""" libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.6" % "test"""",
""" )"""
)
val d = Files.createTempDirectory("test")
Files.write(d.resolve("build.sbt"), buildSbt, StandardCharsets.UTF_8)
val project = d.resolve("project")
Files.createDirectory(project)
Files.write(project.resolve("build.properties"), List("sbt.version=0.13.9"), StandardCharsets.UTF_8)
val solutionTargetPath = d.resolve("src").resolve("main").resolve("scala")
Files.createDirectories(solutionTargetPath)
Files.write(solutionTargetPath.resolve("UserSolution.scala"), List("package tests", s"object SleepInSolution {$solution}"), StandardCharsets.UTF_8)
val testTargetPath = d.resolve("src").resolve("test").resolve("scala")
Files.createDirectories(testTargetPath)
val testSourcePath = Paths.get(appAbsolutePath, "test", "tests")
Files.walkFileTree(testSourcePath, new SimpleFileVisitor[Path] {
override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
Files.copy(file, testTargetPath.resolve(testSourcePath.relativize(file)))
FileVisitResult.CONTINUE
}
})
val sbtCommands = Seq("sbt", "-Dsbt.log.noformat=true", "test")
val output = new StringBuilder
Process(sbtCommands, d.toFile).!(ProcessLogger(line => output append line append "\n"))
output.toString()
//TODO: we need to clean all temp folders
}.getOrElse("Test failed")
}
}
示例7: ModuleTools
//设置package包名称以及导入依赖的类
package dynamicmodulemonitor
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory
import scala.sys.process.Process
object ModuleTools {
val loadingdock_path = ConfigFactory.load().getString("loadingdock_path")
val logger = LoggerFactory.getLogger("ModuleTools")
def scalaCLIPath(): String = if (System.getProperty("os.name") contains "Windows") "scala.bat" else "scala"
def moduleLauncher(modulefilename: String): Unit = {
logger.info(s"Module $modulefilename launching.")
val process = Process(
Seq(
scalaCLIPath(),
"-nc",
s"$loadingdock_path$modulefilename"
)
).lineStream_!
for(output <- process) {
logger.info(s"($modulefilename) $output")
}
logger.info(s"Module $modulefilename has finished.")
}
}
示例8: NowPlaying
//设置package包名称以及导入依赖的类
import java.io.File
import java.net.URLDecoder
import scala.sys.process.{ Process, ProcessIO }
import scala.io.Source
object NowPlaying {
def main(args: Array[String]): Unit = {
val processBuilder = Process("qdbus-qt5 org.mpris.MediaPlayer2.audacious /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Metadata")
val processIo = new ProcessIO(
_ => (),
stdout => {
val wantedLines = Source.fromInputStream(stdout).getLines().map { line =>
val values = line.split(": ")
if(values.length > 0) {
(values(0), values.drop(1).foldLeft("")((x, y) => x + y))
} else {
("", "")
}
}.toMap.filter(x => x._1 == "xesam:title" || x._1 == "xesam:artist" || x._1 == "xesam:url")
val nowPlayingResult = NowPlayingResult(wantedLines.get("xesam:title"), wantedLines.get("xesam:artist"), wantedLines.get("xesam:url"))
nowPlayingResult match {
case NowPlayingResult(None, None, url) => {
val filename = new File(url.get).getName
val decodedFilename = URLDecoder.decode(filename, "UTF-8")
println(s"/me is playing $decodedFilename")
}
case NowPlayingResult(title, artist, _) => println(s"/me is playing ${artist.get} - ${title.get}")
case _ => println("/me is playing I have no idea")
}
},
_ => ()
)
processBuilder.run(processIo)
}
}
case class NowPlayingResult(title: Option[String], artist: Option[String], absolutePath: Option[String])
示例9: createCommand
//设置package包名称以及导入依赖的类
package services
import java.io.File
import scala.sys.process.ProcessLogger
import scala.sys.process.Process
import model.CodeEntity
def createCommand(commandName: String, osName:String = null): String = {
var os = osName
if(os == null) {
os = System.getProperty("os.name")
}
if (os.toLowerCase().contains("win")) {
return commandName + ".bat "
}else {
return commandName+" ";
}
}
}
示例10: ProtractorSpec
//设置package包名称以及导入依赖的类
import org.scalatestplus.play.{OneServerPerSuite, PlaySpec}
import play.api.libs.ws.WSClient
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.Source._
import scala.sys.process.{Process, ProcessIO}
class ProtractorSpec extends PlaySpec with OneServerPerSuite {
"my application" should {
"pass the protractor tests" in {
val baseUrl = s"http://localhost:$port/"
val wsClient = app.injector.instanceOf[WSClient]
val resp = Await.result(wsClient.url(baseUrl).get(), 2.seconds)
resp.status must be(200)
println(s"Executing protractor using command: 'npm run e2e -- --baseUrl $baseUrl")
runProtractorTests(baseUrl) must be(0)
}
}
private def runProtractorTests(baseUrl: String): Int = {
Process(s"npm run e2e -- --baseUrl $baseUrl", app.getFile("ui"))
.run(pipingInputAndOutput)
.exitValue()
}
private def pipingInputAndOutput = new ProcessIO(_ => (),
stdout => fromInputStream(stdout).getLines().foreach(println),
stderr => fromInputStream(stderr).getLines().foreach(println)
)
}
示例11: using
//设置package包名称以及导入依赖的类
package com.github
import java.util.Locale
import com.github.scaruby.com.github.scaruby.typeclass.CommandSequenceFactory
import scala.language.reflectiveCalls
import scala.sys.process.Process
package object scaruby {
final val DefaultEncoding: String = "UTF-8"
final val DefaultLocale: Locale = Locale.getDefault
def using[A <: { def close(): Unit }, B](resource: A)(block: A => B): B = {
try {
block(resource)
} finally {
resource.close()
}
}
def system[A:CommandSequenceFactory](command: A, cwd: SFile = SFile("."), extraEnv: Seq[(String, String)] = Seq.empty): String = {
val adapter = implicitly[CommandSequenceFactory[A]]
Process(adapter.newInstanceFrom(command), cwd.file, extraEnv:_*).!!
}
}
示例12: DockerBuildAction
//设置package包名称以及导入依赖的类
package com.criteo.dev.cluster.docker
import com.criteo.dev.cluster.DevClusterProcess
import org.slf4j.LoggerFactory
import scala.collection.mutable.ListBuffer
import scala.sys.process.{Process, ProcessLogger}
class DockerBuildAction (dockerFile: String, dockerImage: String) {
private val logger = LoggerFactory.getLogger(classOf[DockerBuildAction])
private val processLogger = ProcessLogger(
(e: String) => logger.info("err " + e))
private val args = new ListBuffer[Pair[String, String]]
private val ports = new ListBuffer[PortMeta]
def addArg(key: String, value: String) = {
args.+=(Pair(key, value))
}
def run() : Unit = {
val sb = new StringBuilder("docker build")
sb.append(s" -t $dockerImage")
sb.append(s" -f ./${DockerConstants.dockerBaseDir}/$dockerFile")
args.foreach(p => sb.append(s" --build-arg ${p._1}=${p._2}"))
sb.append(s" ${DockerConstants.dockerBaseDir}")
val out = DevClusterProcess.process(sb.toString).!
if (out != 0) {
throw new Exception("Failure running docker command.")
}
}
}
object DockerBuildAction {
def apply(dockerFile: String, dockerImage: String) = {
val dba = new DockerBuildAction(dockerFile, dockerImage)
dba.run
}
}
示例13: StartLocalCliAction
//设置package包名称以及导入依赖的类
package com.criteo.dev.cluster.docker
import com.criteo.dev.cluster.aws.AwsUtilities.NodeRole
import com.criteo.dev.cluster._
import com.criteo.dev.cluster.config.GlobalConfig
import org.slf4j.LoggerFactory
import scala.sys.process.Process
@Public object StartLocalCliAction extends CliAction[Unit] {
private val logger = LoggerFactory.getLogger(StartLocalCliAction.getClass)
override def command: String = "start-local"
override def usageArgs: List[Any] = List(Option("instanceId"))
override def help: String = "Starts a local cluster docker container. If instanceId specified, " +
"only start that one container, else starts them all."
override def applyInternal(args: List[String], config: GlobalConfig): Unit = {
val conf = config.backCompat
//instance id is optional
val instanceId = if (args.length == 1) Some(args(0)) else None
val dockerMetas = DockerUtilities.getDockerContainerMetadata(
DockerConstants.localClusterContainerLabel,
instanceId)
dockerMetas.foreach(d => {
val command = s"docker start ${d.id}"
DevClusterProcess.process (command).!!
//add other required confs needed by the setup action (target ip, port)
val dockerCluster = NodeFactory.getDockerNode(config.target.local, d)
DockerUtilities.blockOnSsh(dockerCluster)
StartServiceAction(dockerCluster, NodeRole.Master)
//print out new docker container info.
val dockerMetas = DockerUtilities.getDockerContainerMetadata(
DockerConstants.localClusterContainerLabel,
instanceId)
DockerUtilities.printClusterDockerContainerInfo(conf, dockerMetas)
})
}
}
示例14: Numpy
//设置package包名称以及导入依赖的类
package testbed
import testbed._
import scala.reflect.io.{File, Path}
import scala.sys.process.{ProcessLogger, Process}
class Numpy[ResultType](val pathToPython: String, numpyImportAlias: String = "np") {
def isInstalled = {
val testPythonCmd = Process(s"$pathToPython --version")
val testNumpyCmd = Process(Seq(pathToPython, "-c", "'import numpy; print(numpy.version)'"))
def pythonInstalled = {
var result = ""
testPythonCmd ! ProcessLogger(line => result += line)
result contains "Python"
}
def numpyInstalled = {
var result = ""
testNumpyCmd ! ProcessLogger(line => result += line)
!(result contains "Error")
}
pythonInstalled && numpyInstalled
}
val NOT_INSTALLED_MSG: String = s"No numpy installation found with $pathToPython."
val PYTHON_SRC_FILE_NAME: String = "src_buffer.py"
def getResult(numpyExpr: String, bufferName: String, resultReader: String => ResultType) = {
assert(isInstalled, NOT_INSTALLED_MSG)
val absolutePathToBuffer = Path(bufferName).toAbsolute.path
val pythonSrcFile = File(PYTHON_SRC_FILE_NAME)
val pythonFileWriteExpr =
s"""import numpy as $numpyImportAlias
|import csv
|with open('$absolutePathToBuffer', 'w') as buffer_file:
| csv_writer = csv.writer(buffer_file, delimiter=',')
| for result_line in $numpyExpr:
| result_line = [result_line]
| csv_writer.writerow(result_line)
""".stripMargin
pythonSrcFile.writeAll(pythonFileWriteExpr)
Process(Seq(pathToPython, pythonSrcFile.toAbsolute.path))!
resultReader(bufferName)
}
}
示例15: ProtractorSpec
//设置package包名称以及导入依赖的类
import org.scalatestplus.play.{OneServerPerSuite, PlaySpec}
import play.api.libs.ws.WSClient
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.Source._
import scala.sys.process.{Process, ProcessIO}
class ProtractorSpec extends PlaySpec with OneServerPerSuite {
"my application" should {
"pass the protractor tests" in {
val baseUrl = s"http://localhost:$port/"
val wsClient = app.injector.instanceOf[WSClient]
val resp = Await.result(wsClient.url(baseUrl).get(), 2.seconds)
resp.status must be(200)
println(s"Executing protractor using command: 'npm run play-e2e -- --baseUrl $baseUrl")
runProtractorTests(baseUrl) must be(0)
}
}
private def runProtractorTests(baseUrl: String): Int = {
var runProtractor: String = "npm run play-e2e -- --baseUrl " + baseUrl
if (System.getProperty("os.name").toLowerCase().contains("win")){
runProtractor = "cmd /c " + runProtractor
}
Process(runProtractor, app.getFile("ui"))
.run(pipingInputAndOutput)
.exitValue()
}
private def pipingInputAndOutput = new ProcessIO(_ => (),
stdout => fromInputStream(stdout).getLines().foreach(println),
stderr => fromInputStream(stderr).getLines().foreach(println)
)
}