Launching subprocess in Ruby plugin - Not entering IF statement when loading from SketchUp

There is some strange behavior happening to me when I launch a subprocess in my Ruby plugin. The purpose is reading a line from the output and getting a substring of that line, the name of the project in this case. I use IO.popen and the code is the following:

my_cmd = 'my_program.exe parameter1 parameter2'
project_name = 'ERROR'

IO.popen my_cmd do |io|
  io.each do |line|
    puts line
    if line.include?('Project created! The name of the project is: ')
      project_name = line.split('Project created! The name of the project is:')[1]
    end
  end
end

UI.messagebox(project_name)

When I launch Sketchup from Rubymine, the code works, and it is entering the IF statement.

image

However, if I open directly SketchUp, as a standard user, the code is not entering the IF statement.

image

Any hint?

Search this category on “popen” and “pipes”.

There was a (somewhat) recent thread about the same kind of issue with backticks.

I think the only reliable way to get another process’ output is to pipe it to a file, then read the file.

I’m pretty familiar with Ruby, and I tried it with SU2018 (Ruby 2.2), SU2019 (Ruby 2.5), and a special SU2019 (Ruby master ~2.7). All do not map IO as one would expect.

Also, any command with pipes/threads, etc that has a block, puts cannot be used in the block

HTH, Greg

1 Like

@MSP_Greg The piping to a file solution is fine, but it doesn’t work if you need to interact with the output. For example, imagine you have to respond a Yes/No question like:

my_cmd = 'my_program.exe parameter1 parameter2'
project_name = 'ERROR'

IO.popen my_cmd do |io|
  io.each do |line|

    if line.include?('Continue? [Y/N]')
      io.puts("Y")
      io.puts("\n")
    end

    if line.include?('Project created! The name of the project is: ')
      project_name = line.split('Project created! The name of the project is:')[1]
    end

  end
end

UI.messagebox(project_name)

If I run my_cmd = 'my_program.exe parameter1 parameter2 > info.log' the process get stuck in the 'Continue? [Y/N]' line.

@Finfa811

Correct. You might be able to use sockets. If you find a solution, feel free to post it. As I stated, I tried a few different ways of using normal IO/pipes, and nothing worked. I may revisit it, but it will be a few days… Greg

1 Like

The moral of the story is that this just does not work in SketchUp because it’s Ruby Console has commandeered STDIN and STDOUT for it’s own use.

There are some threads around (here or at SCF) where some coders have used external VBS scripts to do this interaction and write out the results to a file. The Ruby code starts the VBS and then starts a timer to check for the existence of the output file. When the file exists and / or is updated with a time after the start time, then the Ruby code processes the file.

1 Like