By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to? return values from @python

What techniques are available to return values from %@python[] to TCC ?
I have been exploring some straightforward ways, but I can't see how to get something out of @python except for console output. Note that I am not using the supported ActivePython but another distribution, so my issue could be all there. Anyways, this is what I tried:
  1. Capture standard output: set x=%@python[print 1+1] >out
    This sets x=0 (python's exit code?), creates an empty out file and prints 2 to the console.
  2. Set a TCC variable from python: how can I do that?
    Incidentally I discovered that the persistent python interpreter gets its own frozen environment block, so setting environment variables, like $PATH, from python is pointless because changes aren't reflected in TCC's environment block.
  3. Write to a file from python. Here is a working example, but I would like to find a memory based solution as well, like #2.
set tmpf=%@unique["%[TEMP]"]
echo>nul %@python[with open(r'%[tmpf]','w') as tmpf: print >>tmpf, 1+1]
type "%[tmpf]"
del "%[tmpf]"
I can't speak for the Python support Stefano, but the equivalent @REXX simply allows you to return a numeric value valid as an exit code (REXX has both EXIT and RETURN 'statements' that can be used to achieve that). Any attempt to return a value that cannot be interpreted as a number (and this might differ for python, REXX has no data typing so all data are effectively strings) causes the TCC instance to crash.
Thanks Steve. I read in an older thread of this forum that performing an exit(n) in python closes the TCC session as well because the python interpreter is persistent.
Just to resurrect this old thread, I found that at least with TCC v25, one can successfully set environment variables in Python and read them in the same TCC session:

> set r=%@python[from os import environ as env]
> set r=%@python[env['pyfoo'] = str(2**16)]
> echo %pyfoo
With this function, I've made Python very easy to integrate into my TCC scripts:

:: User-defined variable function
PyEval=%@IF[%@python["import os; os.environ['PyEval_Output'] = str(%$)"] == 0,%PyEval_Output,]

And so one can do things like

> set nums=%@PyEval["-".join(str(i) for i in range(1,11))]
> echo %nums


Similar threads