• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Process类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.sys.process.Process的典型用法代码示例。如果您正苦于以下问题:Scala Process类的具体用法?Scala Process怎么用?Scala Process使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Process类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:bobxwang,项目名称:scalatour,代码行数:28,代码来源:SysPropertiesTest.scala


示例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")
  }

} 
开发者ID:meetup,项目名称:scala-logger,代码行数:29,代码来源:LoggingComponentTest.scala


示例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`")
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:44,代码来源:GenerateFixtures.scala


示例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()
  }
} 
开发者ID:teapot-co,项目名称:tempest,代码行数:57,代码来源:TempestDBServerClientSpec.scala


示例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)
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:37,代码来源:Main.scala


示例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")
  }
} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:52,代码来源:SbtTestRunner.scala


示例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.")
  }

} 
开发者ID:ClydeMachine,项目名称:DynamicModuleMonitor,代码行数:31,代码来源:ModuleTools.scala


示例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]) 
开发者ID:nadams,项目名称:now-playing,代码行数:44,代码来源:NowPlaying.scala


示例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+" ";
    }
  }

} 
开发者ID:AdamGuar,项目名称:scala-compiler-service,代码行数:23,代码来源:FileRunner.scala


示例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)
  )

} 
开发者ID:vinhbt,项目名称:statistic,代码行数:39,代码来源:ProtractorSpec.scala


示例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:_*).!!
  }

} 
开发者ID:scaruby,项目名称:scaruby,代码行数:26,代码来源:package.scala


示例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
  }
} 
开发者ID:criteo,项目名称:berilia,代码行数:44,代码来源:DockerBuildAction.scala


示例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)
    })
  }
} 
开发者ID:criteo,项目名称:berilia,代码行数:47,代码来源:StartLocalCliAction.scala


示例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)
  }
} 
开发者ID:bethge,项目名称:sketching-testbed,代码行数:56,代码来源:Numpy.scala


示例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)
  )

} 
开发者ID:lbialy,项目名称:play-ng2-webpack2,代码行数:43,代码来源:ProtractorSpec.scala


示例16: echo

//设置package包名称以及导入依赖的类
package util.process

import text.{StringNone, StringSome}
import text.normalizer.NormalizedString

import scala.sys.process.{Process, ProcessBuilder}


trait EchoProcess {
  def echo(str: String): ProcessBuilder = {
    Process(Seq("/usr/bin/printf", str.toString))
  }

  def echo(sentence: NormalizedString): ProcessBuilder = {
    sentence.toStringOption match {
      case StringSome(s) =>
        echo(s.toString)
      case StringNone =>
        Process(Nil)
    }
  }
} 
开发者ID:ktr-skmt,项目名称:FelisCatusZero,代码行数:23,代码来源:EchoProcess.scala


示例17: Showcase

//设置package包名称以及导入依赖的类
package text.analyzer.dep.chapas

import java.nio.charset.{CodingErrorAction, StandardCharsets}

import text.StringNone
import text.analyzer.dep.cabocha.CaboCha
import text.normalizer.NormalizedString
import util.{SentenceUnitReconstructorConfig, ShowcaseCache}
import util.process.EchoProcess
import util.process.ProcessBuilderUtils._


import scala.sys.process.Process


object Showcase extends PasAnalyzer with EchoProcess with ShowcaseCache {
  private val showcaseCmd: String = {
    SentenceUnitReconstructorConfig.showcase match {
      case Some(c) => c
      case None => throw new RuntimeException("Showcase command was not found.")
    }
  }

  override def analyze(sentence: NormalizedString): Iterator[String] = {
    CaboCha.cabochaLatticeJumanCmd(sentence).#|(Process(showcaseCmd)).lineStream(
      StandardCharsets.UTF_8,
      CodingErrorAction.IGNORE,
      CodingErrorAction.IGNORE,
      StringNone
    )
  }

  override def cabochaLattice(sentence: NormalizedString): Iterator[String] = {
    CaboCha.cabochaLatticeJumanCmd(sentence).lineStream(
      StandardCharsets.UTF_8,
      CodingErrorAction.IGNORE,
      CodingErrorAction.IGNORE,
      StringNone
    )
  }

  override def cabochaTree(sentence: NormalizedString): Iterator[String] = {
    CaboCha.cabochaTreeJumanCmd(sentence).lineStream(
      StandardCharsets.UTF_8,
      CodingErrorAction.IGNORE,
      CodingErrorAction.IGNORE,
      StringNone
    )
  }

  override final protected[this] def textToDoc(normalizedSentencesOption: NormalizedString): Doc =
    (if (cacheEnable) getDocCache(normalizedSentencesOption) else None) getOrElse
      this.parser.parse(analyze(normalizedSentencesOption))

  override val parser: ShowcaseNtcParser.type = ShowcaseNtcParser
} 
开发者ID:ktr-skmt,项目名称:FelisCatusZero,代码行数:57,代码来源:Showcase.scala


示例18: CaboCha

//设置package包名称以及导入依赖的类
package text.analyzer.dep.cabocha

import text.normalizer.NormalizedString
import util.SentenceUnitReconstructorConfig
import util.process.EchoProcess

import scala.sys.process.{Process, ProcessBuilder}
import scala.util.matching.Regex


object CaboCha extends EchoProcess {
  final private[this] val cabochaLatticeIPA: String = {
    SentenceUnitReconstructorConfig.cabochaLatticeIPA match {
      case Some(c) => c
      case None    => throw new RuntimeException("CaboCha lattice with IPA command was not found.")
    }
  }

  def cabochaLatticeIPACmd(sentence: NormalizedString): ProcessBuilder =
    echo(sentence) #| Process(cabochaLatticeIPA)

  final private[this] val cabochaTreeIPA: String = {
    SentenceUnitReconstructorConfig.cabochaTreeIPA match {
      case Some(c) => c
      case None    => throw new RuntimeException("CaboCha tree with IPA command was not found.")
    }
  }

  def cabochaTreeIPACmd(sentence: NormalizedString): ProcessBuilder =
    echo(sentence) #| Process(cabochaTreeIPA)

  final private[this] val cabochaLatticeJuman: String = {
    SentenceUnitReconstructorConfig.cabochaLatticeJuman match {
      case Some(c) => c
      case None    => throw new RuntimeException("CaboCha lattice with Juman command was not found.")
    }
  }

  def cabochaLatticeJumanCmd(sentence: NormalizedString): ProcessBuilder =
    echo(sentence) #| Process(cabochaLatticeJuman)

  final private[this] val cabochaTreeJuman: String = {
    SentenceUnitReconstructorConfig.cabochaTreeJuman match {
      case Some(c) => c
      case None    => throw new RuntimeException("CaboCha tree with Juman command was not found.")
    }
  }

  def cabochaTreeJumanCmd(sentence: NormalizedString): ProcessBuilder =
    echo(sentence) #| Process(cabochaTreeJuman)

  final val treeChunkRegExp: Regex = """(\s*)([^-D]*)(-*D?.*)""".r
} 
开发者ID:ktr-skmt,项目名称:FelisCatusZero,代码行数:54,代码来源:CaboCha.scala


示例19: IndriIndex

//设置package包名称以及导入依赖的类
package ir.fulltext.indri

import java.nio.charset.{CodingErrorAction, StandardCharsets}
import java.nio.file.Path

import text.StringNone
import util.Config

import scala.collection.mutable.ListBuffer
import scala.sys.process.Process


class IndriIndex(inputPath: Path, indexPath: Path) {
  private def command: Seq[String] = {
    Seq[String](
      "IndriBuildIndex",
      "-field.name=TITLE",
      "-memory=".concat(Config.indriMemory),
      "-corpus.path=".concat(inputPath.toAbsolutePath.toString),
      "-corpus.class=trectext",
      "-index=".concat(indexPath.toAbsolutePath.toString)
    )
  }

  def index(): Unit = {
    val buffer: ListBuffer[String] = ListBuffer.empty[String]
    command.foreach(buffer.+=)
    import util.process.ProcessBuilderUtils._
    Process(buffer.result).lineStream(
      StandardCharsets.UTF_8,
      CodingErrorAction.IGNORE,
      CodingErrorAction.IGNORE,
      StringNone
    ).foreach(println)
  }
} 
开发者ID:ktr-skmt,项目名称:FelisCatusZero,代码行数:37,代码来源:IndriIndex.scala


示例20: IndriIndexer

//设置package包名称以及导入依赖的类
package us.feliscat.ir.fulltext.indri

import java.nio.charset.{CodingErrorAction, StandardCharsets}
import java.nio.file.Path

import us.feliscat.text.StringNone
import us.feliscat.util.LibrariesConfig
import us.feliscat.util.process._

import scala.collection.mutable.ListBuffer
import scala.concurrent.duration._
import scala.sys.process.Process


class IndriIndexer(inputPath: Path, indexPath: Path) {
  private def command: Seq[String] = {
    "IndriBuildIndex" ::
    "-field.name=TITLE" ::
    "-memory=".concat(LibrariesConfig.indriMemory) ::
    "-corpus.path=".concat(inputPath.toAbsolutePath.toString) ::
    "-corpus.class=trectext" ::
    "-index=".concat(indexPath.toAbsolutePath.toString) :: Nil
  }

  def index(): Unit = {
    val buffer = ListBuffer.empty[String]
    command.foreach(buffer.+=)
    Process(buffer.result).lineStream(
        StandardCharsets.UTF_8,
        CodingErrorAction.IGNORE,
        CodingErrorAction.IGNORE,
        StringNone,
        LibrariesConfig.indriBuildIndexTimeout.minute
      ).foreach(println)
  }
} 
开发者ID:ktr-skmt,项目名称:FelisCatusZero-multilingual,代码行数:37,代码来源:IndriIndexer.scala



注:本文中的scala.sys.process.Process类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ZoneId类代码示例发布时间:2022-05-23
下一篇:
Scala Buffer类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap