gurkensaas
gurkensaas

Reputation: 913

How can you detect NaN in Applescript?

So I have a python script that does some math that I call via do shell script like this:

return do shell script "/usr/local/bin/python3.9 /path/to/my/file.py"
(*Python file returns something like this:
...
25.537989061650084
27.01428839325525
nan
nan
23.678689253368486
nan
35.00336192227798
37.77710795005522
37.70807585046893
38.02099024474269
37.2270982297317
36.90066402440177
37.00379510935199
...
*)

The NaN's in there are no problem, however, I want to filter them out. I have a function that removes items from lists and as soon as a nan appears, I want to filter it out.

I tried multiple methods:

set theParagraphs to paragraphs of (do shell script "/usr/local/bin/python3.9 /path/to/my/file.py")
repeat with currentItem in theParagraphs
    try
        set currentItem to currentItem as number --produces no error
        set currentItem to currentItem + 0 --produces no error
    on error
        --remove item from list here
    end try
    
    if currentItem is equal to "nan" then -- False 
        --remove item from list here
    end if
    
    if currentItem is not equal to currentItem then --False
        --remove item from list here
    end if
end repeat

Is there any easy way to either get it to produce an error or compare it to anything?

Upvotes: 0

Views: 95

Answers (2)

CJK
CJK

Reputation: 6092

set my text item delimiters to {["NaN\n"], "\nNaN"}
set sh to "/usr/local/bin/python3.9 /path/to/my/file.py"
set py to (do shell script sh)'s text items as text
set R to every paragraph of py

If you want them as numbers rather than numerical strings, the most conventional way would be to iterate and coerce:

repeat with x in a reference to R
    tell x to set its contents ¬
        to the contents as real
end repeat

Upvotes: 2

gurkensaas
gurkensaas

Reputation: 913

I ended up checking it in the Python Script using:

if str(result) != "nan":
    print(result)

Upvotes: 0

Related Questions