1

I am trying to run compile below function in scala

  import java.io.{File, PrintWriter, StringWriter}
  def runCommand(cmd:String):(Int,String)={
      try {
        logger.info(String.format("Trying to run the following bash command: [%s]", cmd))
        import sys.process._
        val intResult:Int = cmd !
        val stringResult:String = cmd !!
        (intResult, stringResult)
      }
      catch {
        case e: Exception => {
          logger.error(String.format("Error in running the following bash command: [%s], Program exits!", cmd))
          val sw = new StringWriter
          e.printStackTrace(new PrintWriter(sw))
          System.out.println(sw.toString)
          sys.exit(1)
        }
      }
    (1,"1")
  }

But, I am getting below error:

[ERROR] [Error] C:\Users\cp740539\IdeaProjects\sparkscala\src\main\scala\au\com\optus\bdp\conversion\PurgingPartitions.scala:213: overloaded method value !! with a
lternatives:
  (log: scala.sys.process.ProcessLogger)String <and>
  => String
 cannot be applied to (Int, String)

I am not sure what is the cause of the erro?

Mah
  • 95
  • 1
  • 1
  • 8
  • I think you have a bug here: you execute the same command twice - via `!` and `!!` method executions. Or is this was done on purpose? – Ivan Kurchenko Mar 12 '21 at 05:10
  • It was on purpose.. – Mah Mar 12 '21 at 05:35
  • Another option that is not recommended (it is deprecated), is to enable postfix. You can read about it at [Scala's “postfix ops”](https://stackoverflow.com/q/13011204/2359227). – Tomer Shetah Mar 14 '21 at 07:25

1 Answers1

2

You're using the dot-less instance method arg syntax without the arg. The compiler goes looking for the arg and finds the (intResult,stringResult) tuple and tries to pass that to the !! method, which doesn't work.

Use cmd.! and cmd.!! instead.

Also: If you use a ProcessLogger then you can capture the exit code (Int), as well as StdOut and StdErr (Strings), with a single execution of cmd instead of invoking it twice, as you are doing now.

jwvh
  • 50,871
  • 7
  • 38
  • 64