Skip to content

Instantly share code, notes, and snippets.

@glennsarti
Last active July 16, 2019 07:01
Show Gist options
  • Save glennsarti/3beec56e4323bebed5eb2afe867143b0 to your computer and use it in GitHub Desktop.
Save glennsarti/3beec56e4323bebed5eb2afe867143b0 to your computer and use it in GitHub Desktop.
C:\Source\tmp\process_spawn> be ruby test.rb
*** back ticks
hello " world
*** %x
hello " world
*** capture3
hello "\"" world
*** process.spawn
hello "\"" world
*** capture3 using Array,Array
hello "\"" world
*** capture3 using Array,String
hello \" world
*** capture3 testcases
Expect:hello world
Actual:hello world
Expect:hello " world
Actual:hello "\"" world
Expect: hello " world
Actual:" hello " " \" " " world "
Expect:hello "" world
Actual:hello "\"\"" world
Expect:hello \" world
Actual:hello "\\\"" world
Expect:hello ^" world
Actual:hello "^\"" world
C:\Source\tmp\process_spawn>
require 'open3'
shell = ['cmd.exe', '/c']
command = ['echo', 'hello', '"', 'world']
#Output
# cmd.exe
# C:\Users\glenn.sarti>echo hello " world
# hello " world
# PowerShell
# C:\Source\tmp\process_spawn> cmd --% /c echo hello " world
# hello " world
puts "\n*** back ticks"
puts `#{shell.join(' ')} #{command.join(' ')}`
# hello " world
puts "\n*** %x"
puts %x[#{shell.join(' ')} #{command.join(' ')}]
puts "\n*** capture3"
cmd = shell.dup.concat(command)
stdout, stderr, t = Open3.capture3(*cmd)
puts stdout
puts "\n*** process.spawn"
cmd = shell.dup.concat(command)
tmpfile = File.join(ENV['TMP'], 'stdout.txt')
pid = Process.spawn(*cmd, :out => tmpfile)
Process.wait pid
File.open(tmpfile, 'rb') { |f| puts f.read }
puts "\n*** capture3 using Array,Array"
cmd = shell.dup.concat(command)
stdout, stderr, t = Open3.capture3(*shell, *command)
puts stdout
puts "\n*** capture3 using Array,String"
cmd = shell.dup
cmd << command.join(' ')
stdout, stderr, t = Open3.capture3(*cmd)
puts stdout
# ---
puts "\n*** capture3 testcases"
[
['hello', 'world'],
['hello', '"', 'world'],
[' hello ', ' " ', ' world '],
['hello', '""', 'world'],
['hello', '\\"', 'world'],
['hello', '^"', 'world'],
].each do |testcase|
cmd = shell.dup.concat(['echo']).concat(testcase)
stdout, stderr, t = Open3.capture3(*cmd)
puts "Expect:#{testcase.join(' ')}\nActual:#{stdout}\n"
end
# Looked at raw FFI...but too hard right now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment