Ruby calls the Python script

As a novice to ruby and python, I wanted to call a python script with ruby, and after some attempts without success, the current situation is that the python script is called but ruby does not return parameters. An example is as follows:
python script:

import sys

def calculate(x, y):
    z = x+y
    return z

if __name__ == '__main__':
    x1 = sys.argv[1]
    y1 = sys.argv[2]
    z1 = calculate(x1, y1)

ruby example of a call:

`python G:/PycharmProjects/learnPython/rubyInvoke/ 1 2`

Returns the result

Please help me see if there is a problem with the code, I hope to get ruby how to get the return result advice

There is nothing wrong with the code. (EDIT: … except what Aerilius notes below.)

The backquote method (aka %x execute strings along with STDIO) in SketchUp’s Ruby has been bugged for quite sometime. I just tested on SketchUp 2017 and it was bugged back then as well.

The workaround is to have the external script or command redirect it’s output to a text file, and then have Ruby read the file using either IO::read or IO::readlines.

Example …
… has no output in Ruby’s Console.

But …
%x[dir > dir.txt]
… and then …
text ="dir.txt")
… works.

By the way, also the Python script does not return anything.

You should start complicated things by focussing on the individual parts and making them work (and test them) before putting them together.

In the Python script, you can use sys.exit(1) to set a return code for “success” or “failure”. I would not return z1 this way because it might not always be an integer.

In order to give the output so that Ruby can read it according to Dan’s example, you need to print (or log) it to standard out, like: print(z1).

1 Like

I’m also not quite sure if this is a Windows only bug ?

This is a trivial thing to do in stand-alone Ruby when run from a command line in a console window. As mentioned above, you need some means of moving the data between scripts, so your python script would need a print statement.

Doing this in SketchUp is rather messy, as it’s not running Ruby as a console app, so there’s no STDOUT to pass string data between it and subprocesses, which python would be.

One can do things like this in SketchUp, but one needs to pass data between it and the subprocess app via sockets, files, etc…

Thank you for your answer, I will try according to your suggestions