1

I'm looking for a more elegant way to do this:

import scala.sys.process._
(Seq("echo", "Mary had a little lamb") #| "code -").!!

In bash I'd do:

code - <<< Mary had a little lamb

I've tried going via an InputStream and getting Scala to accept it as a Source so the Process can use it for its stdin alas scalac did not like what I offered.

phdoerfler
  • 470
  • 6
  • 19

1 Answers1

1

You haven't included your InputStream attempt so it's hard to know if this is what you're after (or if it is "elegant" enough).

import scala.sys.process._
import scala.language.postfixOps
import java.io.{ByteArrayInputStream => BAIS}
import java.nio.charset.StandardCharsets.UTF_8

val bais = new BAIS("Mary had a little lamb\n".getBytes(UTF_8))

"code -" #< bais !!
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Interesting! My first reaction when I saw your answer was "Hu, haven't I tried exactly this??" and indeed I have done: `import scala.sys.process._; ("code -" <# (new java.io.ByteArrayInputStream("meep".getBytes))).!!` and it failed and still fails with `error: value <# is not a member of String`. – phdoerfler Apr 29 '21 at 07:24
  • /sighs/ Turns out, I wrote `<#` instead of `#<` and staring at it for an extended period of time clearly did not help seeing that mistake. Mystery solved! – phdoerfler Apr 29 '21 at 07:30
  • (Also kudos for spotting the "\n", I was debating whether I should use "echo -n" in my example instead of just "echo" but especially on SO I find that any additional character in the question invites people to just gloss over it and give a non helpful answer.) – phdoerfler Apr 29 '21 at 07:36
  • I have mixed feelings about specifying an encoding. I'm normally the first to add explicit encodings to my string handling, but here you'd have to know which encoding the called process expects. Unless specified otherwise this would be the platform's default charset whatever that may be and that's also what you get when you don't explicitly set the encoding. In other words: Explicitly specifying the charset when talking to spawned processes likely does more harm than good. – phdoerfler Apr 29 '21 at 07:41
  • 1
    When testing I used `wc` in place of your `code -` and added the `\n` to get the same results as seen via the command line. I don't have much `InputStream` experience so I copied that code from a [previous SO answer](https://stackoverflow.com/a/782183/4993128). – jwvh Apr 29 '21 at 08:00