Date   

Re: Inconsistent return values

Pavel Koneski
 

I'm relatively new to ironpython and trying to understand my options for returning values back to my C# app. Can someone explain why option 1 returns fine, but option 2 returns null. Trying to allow my web app users to code up some "formulas" (basic logic) and this seems like a great option, but I need to understand "the rules". The responses will be sometimes text and sometimes numeric so wrapping in json.dumps seems like a good plan.

Thanks!!!
Deanna

-------- option 1 (returns "last line") ----------
import json
json.dumps("last line")

--------- option 2 (returns null) -----------
import json
if True==True:
json.dumps("true!!!")
else:
json.dumps("false!!!”)
On 27 Oct, 2020, at 01:27, Markus Schaber <m.schaber@...> wrote:

Hi, Deanna,

I think it‘s the difference between a statement and an expression.

Statements don’t have return values in general, only if they’re expressions. “if”-statements are not expressions.

My guess is: If the last statement is an expression, it uses it’s result as return value, and None otherwise.
Frankly it looks like a bug to me. Statements have a value, although it is often None, the value of if/else should be the value of the last statement in the executed branch.

As a workaround, you may try:

```
import json
if True==True:
res = json.dumps("true!!!")
else:
res = json.dumps("false!!!”)
res
```

Deanna, you may get a more decisive response on the Gitter chat[1], which is more active than this mailing list.

Regards,
Pavel Koneski

[1]: https://gitter.im/IronLanguages/ironpython


Re: Inconsistent return values

Markus Schaber
 

Hi, Deanna,

I think it‘s the difference between a statement and an expression.

 

Statements don’t have return values in general, only if they’re expressions. “if”-statements are not expressions.

 

My guess is: If the last statement is an expression, it uses it’s result as return value, and None otherwise.

 

 

 

Mit freundlichen Grüßen / Best regards

Markus Schaber


CODESYS Group
We
software Automation.


CODESYS Development GmbH
A member of the CODESYS Group

Dipl.-Inf.
Markus Schaber | Team Leader Automation Server
Tobias-Dannheimer-Str. 5 | 87439 Kempten | Germany
Tel. +49-831-54031-979
m.schaber@... | codesys.com

CODESYS Store: store.codesys.com
CODESYS Talk: forge.codesys.com
CODESYS Online Help: help.codesys.com


Geschäftsführer / CEOs: Dipl.-Inf. Dieter Hess, Dipl.-Inf. Manfred Werner
Handelsregister / Trade register: Kempten HRB 13379
| USt-IDNr. / Tax ID No.: DE 307355786


Diese E-Mail enthält möglicherweise vertrauliche und/oder rechtlich geschützte Informationen. Wenn Sie nicht der richtige Adressat sind
oder diese E-Mail irrtümlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese Mail.
Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser Mail ist nicht gestattet.

This e-mail may contain confidential and/or privileged information. If you are not the intended recipient or have received
this e-mail in error, please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure
or distribution of the material in this e-mail is strictly forbidden.

Von: users@ironpython.groups.io <users@ironpython.groups.io> Im Auftrag von ddelapasse@...
Gesendet: Freitag, 23. Oktober 2020 21:59
An: users@ironpython.groups.io
Betreff: [ironpython] Inconsistent return values

 

Hi,

I'm relatively new to ironpython and trying to understand my options for returning values back to my C# app.  Can someone explain why option 1 returns fine, but option 2 returns null.   Trying to allow my web app users to code up some "formulas" (basic logic) and this seems like a great option, but I need to understand "the rules".   The responses will be sometimes text and sometimes numeric so wrapping in json.dumps seems like a good plan.

Thanks!!!
Deanna

-------- option 1 (returns "last line") ----------

import json

json.dumps("last line")


---------    option 2 (returns null)     -----------
import json

if True==True:

   json.dumps("true!!!")

else:

   json.dumps("false!!!")

 


Inconsistent return values

ddelapasse@...
 

Hi,

I'm relatively new to ironpython and trying to understand my options for returning values back to my C# app.  Can someone explain why option 1 returns fine, but option 2 returns null.   Trying to allow my web app users to code up some "formulas" (basic logic) and this seems like a great option, but I need to understand "the rules".   The responses will be sometimes text and sometimes numeric so wrapping in json.dumps seems like a good plan.

Thanks!!!
Deanna

-------- option 1 (returns "last line") ----------
import json
json.dumps("last line")

---------    option 2 (returns null)     -----------
import json
if True==True:
   json.dumps("true!!!")
else:
   json.dumps("false!!!")



How to reset and clear Ironpython Console?

Henry Li
 

It seems that there is no command to reset console to initial state, clear the content and leave history intact. Is there any way to do that ? or programmatically to do that?  


How to clear and reset IronPython Console? is there any way to clear ScriptScope?

Henry Li
 

Is there way to clear or reset Console like IPython?  It seems command of clear or reset doesn't work.

Or how to reset ScriptScope or Engine?  I've created a console and set initial state, I expect that user can reset it to initial state after some input. a simple example is
initial state:
import math
global = 100

after input 
x=0
y=100
....
then I want to reset it to the initial state, how can I remove/delete input of "x=0, y=0, ..."?


Re: I can't import random module

javierfernandezc@...
 

Thanks Markus, this is the best solution, a simple "from System import...", and use random object.


Re: I can't import random module

Markus Schaber
 

Hi,

 

As it’s IronPython, you could also use the .NET Framework random generators. J

 

Mit freundlichen Grüßen / Best regards

Markus Schaber


CODESYS Group
We
software Automation.


CODESYS Development GmbH
A member of the CODESYS Group

Dipl.-Inf.
Markus Schaber | Team Leader Automation Server
Tobias-Dannheimer-Str. 5 | 87439 Kempten | Germany
Tel. +49-831-54031-979
m.schaber@... | codesys.com

CODESYS Store: store.codesys.com
CODESYS Talk: forge.codesys.com
CODESYS Online Help: help.codesys.com


Geschäftsführer / CEOs: Dipl.-Inf. Dieter Hess, Dipl.-Inf. Manfred Werner
Handelsregister / Trade register: Kempten HRB 13379
| USt-IDNr. / Tax ID No.: DE 307355786


Diese E-Mail enthält möglicherweise vertrauliche und/oder rechtlich geschützte Informationen. Wenn Sie nicht der richtige Adressat sind
oder diese E-Mail irrtümlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese Mail.
Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser Mail ist nicht gestattet.

This e-mail may contain confidential and/or privileged information. If you are not the intended recipient or have received
this e-mail in error, please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure
or distribution of the material in this e-mail is strictly forbidden.

Von: users@ironpython.groups.io <users@ironpython.groups.io> Im Auftrag von javierfernandezc@...
Gesendet: Mittwoch, 30. September 2020 18:36
An: users@ironpython.groups.io
Betreff: Re: [ironpython] I can't import random module

 

[Edited Message Follows]

Finally, I have chosen to make my own random choice function instead:

def RandomChoice(list):

    secondsMII = int((datetime.utcnow() - datetime(2000, 1, 1)).total_seconds() * 1000)

    randomIndex = secondsMII % len(list)

    return list[randomIndex]


Re: I can't import random module

javierfernandezc@...
 
Edited

Finally, I have chosen to make my own random choice function instead:

def RandomChoice(list):

    secondsMII = int((datetime.utcnow() - datetime(2000, 1, 1)).total_seconds() * 1000)

    randomIndex = secondsMII % len(list)

    return list[randomIndex]


Re: I can't import random module

Alex Earl
 

Hi Javier,


This is done because not all users need the stdlib and so the stdlib can be modified without doing a new IronPython release.

Regards,

Alex

On Wed, Sep 30, 2020 at 8:08 AM <javierfernandezc@...> wrote:
Thanks so much for your quick response, Alex.

I am using the IronPython nuget package (version 2.7.5) into a .Net project. Sorry in advance for my ignorance, but stdlib should be included within IronPython.dll, isn't it?

Kind regards,
Javier Fernández




Re: I can't import random module

javierfernandezc@...
 

Thanks so much for your quick response, Alex.

I am using the IronPython nuget package (version 2.7.5) into a .Net project. Sorry in advance for my ignorance, but stdlib should be included within IronPython.dll, isn't it?

Kind regards,
Javier Fernández


Re: I can't import random module

Alex Earl
 

Do you have the StdLib added to your path? random.py is in the Python stdlib and it imports the _random module from IronPython.Modules. Without the stdlib, you can't import random.


On Wed, Sep 30, 2020 at 7:31 AM <javierfernandezc@...> wrote:
I have already seen that, thanks. I tried that and failed againg:

clr.AddReferenceByName('IronPython.Modules')
from IronPython.Modules import *
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))  

ERROR: No module named random




Re: I can't import random module

javierfernandezc@...
 

I have already seen that, thanks. I tried that and failed againg:

clr.AddReferenceByName('IronPython.Modules')
from IronPython.Modules import *
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))  

ERROR: No module named random


Re: I can't import random module

Shush
 

On Wednesday, 30 September 2020, 04:36:18 PM IST, javierfernandezc@... <javierfernandezc@...> wrote:


I would like to run a code like this:

import random
 
def runScript():
    foo = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(foo))  

But I have this error:

"no module named random"


I can't import random module

javierfernandezc@...
 

I would like to run a code like this:

import random
 
def runScript():
    foo = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(foo))  

But I have this error:

"no module named random"


Re: Threading

Markus Schaber
 

Hello,

 

I’m not that deep into the details, but the IronPython threading module internally uses .NET APIs like System.Thread to create and manage its threads. So IronPython Threads are effectively equal to .NET Threads, only with Python API layer on top.

 

Usually, Threads are distributed to different cores if you don’t configure threads explicitly – however, you’re also responsible for proper synchronization, and the IronPython semantics differ from the normal cPython semantics as IronPython has no global interpreter lock.

 

Mit freundlichen Grüßen / Best regards

Markus Schaber


CODESYS Group
We
software Automation.


CODESYS Development GmbH
A member of the CODESYS Group

Dipl.-Inf.
Markus Schaber | Team Leader Automation Server
Tobias-Dannheimer-Str. 5 | 87439 Kempten | Germany
Tel. +49-831-54031-979
m.schaber@... | codesys.com

CODESYS Store: store.codesys.com
CODESYS Forum: forum.codesys.com
CODESYS Online Help: help.codesys.com


Geschäftsführer / CEOs: Dipl.-Inf. Dieter Hess, Dipl.-Inf. Manfred Werner
Handelsregister / Trade register: Kempten HRB 13379
| USt-IDNr. / Tax ID No.: DE 307355786


Diese E-Mail enthält möglicherweise vertrauliche und/oder rechtlich geschützte Informationen. Wenn Sie nicht der richtige Adressat sind
oder diese E-Mail irrtümlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese Mail.
Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser Mail ist nicht gestattet.

This e-mail may contain confidential and/or privileged information. If you are not the intended recipient or have received
this e-mail in error, please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure
or distribution of the material in this e-mail is strictly forbidden.

Von: users@ironpython.groups.io <users@ironpython.groups.io> Im Auftrag von Hailiang Shen
Gesendet: Freitag, 5. Juni 2020 16:52
An: users@ironpython.groups.io
Betreff: [ironpython] Threading

 

Hello all, could I get your help in understanding the IronPython threading module, specifically:

-          is it different from the .NET System.Thread class e.g. in implementation and performance?

-          with the IronPython threading module, if I created a number of N threads, will they be distributed by the operation system (e.g. Windows in my case) to different cores of a CPU to optimize the workload?

 

Your input is greatly appreciated.

 

Hailiang


How to redirect process output to WinForm textbox in real-time?

Hailiang Shen
 

Hello all, I am trying to run a python3 script with .NET Process class. The python3 script runs slow and prints progress along the way, so I’d like to redirect the process prints to a WinFrom textbox.

 

My program includes a few threads:

Thread1 – generates a WinForm and puts it in Thread2

Thread2 – launches the python3 script in Thread3 using .NET Process class

Thread3 – redirects the process prints to a WinForm textbox (in Thread2) in real-time

 

I tried to Invoke the textbox Text update, .NET Mutex class but the process is always dumped at the end of the process but not in real-time.

 

Could you advise what else I may try? Thanks,

 

Hailiang

 


Threading

Hailiang Shen
 

Hello all, could I get your help in understanding the IronPython threading module, specifically:

  • is it different from the .NET System.Thread class e.g. in implementation and performance?
  • with the IronPython threading module, if I created a number of N threads, will they be distributed by the operation system (e.g. Windows in my case) to different cores of a CPU to optimize the workload?

 

Your input is greatly appreciated.

 

Hailiang


Having hard time passing VARIANT* input Parameter to a COM object.

shkshk90+ironpython@...
 

Hello,

 

This was probably answered several times, and I checked almost every documentation available online, and stackOverflow, and nothing seems to work.

At my company, we are using an internal tool, that has a COM object, and we want to call it from IronPython.
The function that I am trying to use, merges several files, and has the following signature (in VBA):
--   object.Merge(VARIANT* pInputListFiles, BSTR strOutputFileName) As Integer
The provided example is as follows (in VBA):
====================================================================

Dim Error As Integer
Dim App As Object
Set App = CreateObject("Viewer.Application")

Dim FileTab
ReDim FileTab(2)
FileTab(0) = "C:\file1.ext"
FileTab(1) = "C:\file2.ext"

Error = App.Merge(FileTab, "C:\file1+2.ext")
MsgBox ("Files Merged")

====================================================================

I am trying to do the the same in IronPython, I created the object successfully, and I can call any function that takes non-Variant input.
However, when a Variant* input is required, that refers to an array, I always get the famous ValueError.

The following happens here's all my trials,

====================================================================

>>> import clr
>>> from System import Array
>>> from System.Runtime.InteropServices import Marshal
>>> from System import String, Single
>>> from System.Type import GetTypeFromProgID
>>> from System.Activator import CreateInstance
>>> apptype= GetTypeFromProgID("Viewer.Application")
>>> app = CreateInstance(apptype)
>>> app.OpenFile(r"C:\file0.txt") # TAKES A BSTR, WORKS FINE
1

>>> app.Merge([r"C:\file1.txt", r"C:\file2.txt"], r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.

>>> app.Merge(Array[string](
[r"C:\file1.txt", r"C:\file2.txt"]), r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.

>>> ref = clr.Reference[Array[String]](Array[String]([r"C:\file1.txt", r"C:\file2.txt"]))
>>> app.Merge(ref, r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.

>>> s1 = clr.Reference[String]()

>>> s1.Value = r"C:\file1.txt"
>>> app.Merge(s1, r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.

>>> s1 = clr.Reference[Array[String]]()
>>> s1.Value = Array[str]([r"C:\file1.txt", r"C:\file2.txt"])
>>> app.Merge(s1, r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.


>>> s2 = clr.Reference[Array[object]]()
>>> s2.Value = Array[
object]([r"C:\file1.txt", r"C:\file2.txt"])
>>> app.Merge(s2, r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.


>>> s2 = clr.Reference[object]()
>>> s2.Value = Array[
object]([r"C:\file1.txt", r"C:\file2.txt"])
>>> app.Merge(s2, r"C:\file3.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Could not convert argument 1 for call to Merge.

>>> ref = clr.Reference[object]()
>>> app.Merge(ref, r"C:\file3.txt") # WORKS FINE, HOWEVER, THIS IS AN IN PARAMETER, NOT OUT
0

====================================================================


I am over my head with this error, does anyone have any idea to guide me?

Documentation and/or links are highly welcomed.

 

I truly appreciate the help.

Thank you so much for your time.

 

Best regards,


Re: Print a float value

Stéphane Lozier
 

The rational number 7/3 cannot be expressed exactly using a float. The result of 7.0/3 is actually 2.333333333333333481363069950020872056484222412109375. So when you round to 17 significant digits you end up with the trailing 35. For more information on floating point numbers I suggest looking at https://en.wikipedia.org/wiki/Double-precision_floating-point_format

Stéphane


On Sun, Mar 22, 2020 at 11:01 AM Hailiang Shen <hailiang@...> wrote:

Thanks Stéphane. This clarified why the results were different. I was also wondering why the 2nd print outputs 2.3333333333333335, where the last digit is not 3 but 5.

 

From: users@ironpython.groups.io <users@ironpython.groups.io> On Behalf Of Stéphane Lozier
Sent: March 22, 2020 10:45 AM
To: users@ironpython.groups.io
Subject: Re: [ironpython] Print a float value

 

In the first case you're printing the float, in the second case you're printing a tuple of floats. In both cases the `__str__` function is called, however in the case of the tuple, `__str__` and `__repr__` are the same so it's like calling `__repr__` of each of its items.

 

>>> class test(object):
...   def __str__(self): return "__str__"
...   def __repr__(self): return "__repr__"
...
>>> print(test())
__str__
>>> print(test(), test())
(__repr__, __repr__)

 

Hope this makes sense.

 

Stéphane

 

On Sat, Mar 21, 2020 at 7:08 PM Hailiang Shen <hailiang@...> wrote:

Hello all, could anyone help me understand printing float values? E.g.

 

print (7.0/3) will output 2.33333333333

print (7/3.0, 7.0/3) will output (2.3333333333333335, 2.3333333333333335)

 

I am not sure why the outputs are slightly different.

 

Regards,

 

Hailiang

 


Re: Print a float value

Hailiang Shen
 

Thanks Stéphane. This clarified why the results were different. I was also wondering why the 2nd print outputs 2.3333333333333335, where the last digit is not 3 but 5.

 

From: users@ironpython.groups.io <users@ironpython.groups.io> On Behalf Of Stéphane Lozier
Sent: March 22, 2020 10:45 AM
To: users@ironpython.groups.io
Subject: Re: [ironpython] Print a float value

 

In the first case you're printing the float, in the second case you're printing a tuple of floats. In both cases the `__str__` function is called, however in the case of the tuple, `__str__` and `__repr__` are the same so it's like calling `__repr__` of each of its items.

 

>>> class test(object):
...   def __str__(self): return "__str__"
...   def __repr__(self): return "__repr__"
...
>>> print(test())
__str__
>>> print(test(), test())
(__repr__, __repr__)

 

Hope this makes sense.

 

Stéphane

 

On Sat, Mar 21, 2020 at 7:08 PM Hailiang Shen <hailiang@...> wrote:

Hello all, could anyone help me understand printing float values? E.g.

 

print (7.0/3) will output 2.33333333333

print (7/3.0, 7.0/3) will output (2.3333333333333335, 2.3333333333333335)

 

I am not sure why the outputs are slightly different.

 

Regards,

 

Hailiang