Python Script help

Posted on
Sat Nov 12, 2016 7:17 pm
dz1rfj offline
Posts: 135
Joined: Mar 13, 2016

Python Script help

I am a casual Mac user, and switched to Indigo because of the Mac Reliability. I am just starting to play with python scripts, and find the ability to create main modules a way to streamline logic into a single location, vs putting similar logic into different files and maintaining multiple versions.

I am struggling with Modules not being found , even though they are in the same folder as one another.

I have stored my scripts here: /Users/brian/Documents/Home Automation/Python Scripts

I can use any of these scripts from inside of Indigo, server, script action, and choose any of the scripts, but I want to leverage reusable functions, and trying to get one script file to import functions from a master script file.

I had no PYTHONPATH, so I tried establishing one to the path above

macserver:~ brian$ echo $PYTHONPATH
/Users/brian/Documents/Home Automation/Python Scripts

It seems I still cannot get the modules to import. I managed to use nano to write a bash file (like I have any idea what that all means :) ) and even included my python folder in the main path statement:

macserver:~ brian$ echo $PATH
/Users/brian/Documents/Home Automation/Python Scripts:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin

It appears I am on an old version of Python, and the tutorials for importing seem to differ depending on the version.
macserver:~ brian$ python --version
Python 2.7.10

Are spaces in the folder structure a problem, I can rename them , just need to tweak my action groups to reflect a new script location, but I can do that if it will help.

Can anyone point me in the right direction?

PS . I am also not a developer, but learning a little every week. I included code below from a file I wrote, welcome any tips on making better python scripts. I find myself making small tweaks during the week. You may notice some references not yet used, like light level, that is for future features.

My biggest frustration learning python was the spacing in python that VBA just does not care about... Thanks to all in this forum for helping me out with that hurdle.

Many thanks!

- Brian




Code: Select all

import datetime
import time
import calendar

airfoilPlugin = indigo.server.getPlugin("com.perceptiveautomation.indigoplugin.Airfoil")
SlidingLightLevel = indigo.devices[495566140]
BackYardLightLevel = SlidingLightLevel.sensorValue * -0.1
myVar = indigo.variables[461896218]  # GoodNight Variable

timestamp = datetime.datetime.now().time() # Throw away the date information
TimetooEarly = datetime.time(9, 30)
TooLate = datetime.time(19)
KitchenOnly = datetime.time(20)

indigo.actionGroup.execute(165084610) # "Audio_SaveAudioState"
indigo.variable.updateValue(1817154897, value=str("Daniel Message: Motion near Basement Door!"))
indigo.actionGroup.execute(1183881012) # "TextBrianLore"


SpeakMessage = "Well, Beam me up Scotty!  Its good to see you old LAD!  Glad you could pop-inn,    we may be enjoying a nice Fire, but , We'll be right down!"

SpeakMessageGarage = "Someone is down near the garage."


def KitchenOnlyspeakers():
    airfoilPlugin.executeAction("connectToSpeaker",props={'speaker':"com.rogueamoeba.group.EE8788B6A5AB46D3B0A46B74895D064A"}) #KitchenOnly
    airfoilPlugin.executeAction("setVolume", props={'volume':"40", 'speakerIds':["3C15C2EF2E0F"]}) # testing
    airfoilPlugin.executeAction("changeAudioSource", props={'sourceType':"application", 'appSource':'com.apple.speech.speechsynthesisd'}) #Speaks Audio

def MuteAll():
 airfoilPlugin.executeAction("setVolume", props={'volume':"0", 'speakerIds':  ["741BB2D2612E","28CFE97EA754","20C9D098FA04","28CFE980B651","3C0754600711","3C15C2EF2E0F"]})

def DayTimeSpeakers():
    airfoilPlugin.executeAction("connectToSpeaker",props={'speaker':"com.rogueamoeba.group.796E96D7229F4750B60A35C3F86BBE4B"})
    airfoilPlugin.executeAction("setVolume", props={'volume':"50", 'speakerIds':  ["741BB2D2612E","28CFE97EA754","20C9D098FA04","28CFE980B651","3C0754600711","3C15C2EF2E0F"]})
    airfoilPlugin.executeAction("changeAudioSource", props={'sourceType':"application", 'appSource':'com.apple.speech.speechsynthesisd'}) #Speaks Audio

MuteAll()


# Its too early , speaks  early Message only in Kitchen
if myVar.value == "false" and indigo.variables[1335916415].value == "false"  and timestamp < TimetooEarly : # not goodnight and Dark out
    #indigo.server.speak("Not Goodnight, and not daytime, but it is before  21 oclock")
    KitchenOnlyspeakers()
    time.sleep(3)
    indigo.server.speak(SpeakMessageGarage)  # Speaks the desired message
    indigo.server.speak("I have turned on some lights for your convenience!")
    indigo.device.turnOn("Backyard Lower Table Lamps")
    indigo.device.turnOff("Backyard Lower Table Lamps", delay=600)
    #indigo.server.speak("Lux level Night")
    time.sleep (16)
    indigo.actionGroup.execute(1142413630) # "Audio_RestoreAudioState"

# Speaks Message on Daytime speakers
if myVar.value == "false" and indigo.variables[1335916415].value == "true" : # Not goodnight and daylight
    indigo.actionGroup.execute(368503121)#Toggles Speaker Mute
    DayTimeSpeakers()
    #indigo.server.speak("Not Goodnight, and daytime")
    time.sleep (3)
    indigo.actionGroup.execute(368503121)#Toggles Speaker Mute
    indigo.server.speak(SpeakMessage)  # Speaks the desired message

    #indigo.server.speak("Lux level Day")
    time.sleep (16)
    indigo.actionGroup.execute(1142413630) # "Audio_RestoreAudioState"

# Speaks URGENT MESSAGE @ Night
if myVar.value == "true" :
    indigo.actionGroup.execute(881497783) # "ag_Urgent Message”
    # Need to account for arriving home late at night, and for dog Motion
    indigo.server.speak("Hello There!  We were not expecting Cabanna Visitors.  Proceed to the front door and ring the door bell.")
    indigo.server.speak("I have turned on some lights for your convenience, also , so I can take good photos of you for the authorities")
    indigo.actionGroup.execute(513003517) # "Backyard On"
    indigo.device.turnOff("Backyard Lower Table Lamps", delay=600)

# Its too late, play only in kitchen
if myVar.value == "false" and indigo.variables[1335916415].value == "false"  and timestamp > KitchenOnly : # plays in kitchen only after 8 PM

    indigo.device.turnOn("Backyard Lower Table Lamps")
    KitchenOnlyspeakers()
    #indigo.server.speak("Not Goodnight, and not daytime, and it is after 20 oclock")
    time.sleep (3)
    indigo.server.speak(SpeakMessageGarage)  # Speaks the desired message
    indigo.server.speak("I have turned on some lights for your visitors convenience!")
   
    indigo.device.turnOff("Backyard Lower Table Lamps", delay=600)
    time.sleep (17)
    indigo.actionGroup.execute(1142413630) # "Audio_RestoreAudioState"



Thanks
-Brian

Posted on
Thu Nov 17, 2016 7:34 pm
dz1rfj offline
Posts: 135
Joined: Mar 13, 2016

Re: Python Script help

Looking for some help using linked python filed in indigo. :?

Does anyone using indigo use linked python files? If so, please share how the modules can be found. Please search my post above for the issue I am having trying to get a module to be found.

Many thanks!

Thanks
-Brian

Posted on
Thu Nov 17, 2016 9:03 pm
DaveL17 offline
User avatar
Posts: 6753
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Python Script help

Here is a very simple example. I created a file and saved it to /Library/Python/2.7/site-packages/foo.py. I needed to enter my administrator credentials to do this.

Code: Select all
#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-

# filename = foo.py

def add(x, y):
   
    return x + y
   
def subtract(x, y):

    return x - y

I then created a second file which can (obviously) be saved anywhere that Indigo can see.
Code: Select all
#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-

# filename = foo1.py

import foo

plus = foo.add(15, 10)

indigo.server.log(str(plus))

minus = foo.subtract(15, 10)

indigo.server.log(str(minus))

Code: Select all
Nov 17, 2016, 8:47:10 PM
   Script                          25
   Script                          5

There are other ways to accomplish what you want, but I like this method because it uses a framework that's familiar. Hope that helps.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Fri Nov 18, 2016 7:02 am
DaveL17 offline
User avatar
Posts: 6753
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Python Script help

If you want to get a little fancier, you can add classes to foo.py. Here's one way to do that.

Code: Select all
#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-

# filename = foo.py

class bar():

    def add(self, x, y):
        return x + y
   
    def subtract(self, x, y):
        return x - y


Code: Select all
#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-

# filename = foo1.py

import foo


apple = foo.bar()

plus  = apple.add(15, 10)
minus = apple.subtract(15, 10)

indigo.server.log(str(plus))
indigo.server.log(str(minus))


I tightened and shuffled a tad to clean things up. I didn't respond to your other question regarding style. You've already learned that spacing is very important in Python--you can use tabs or spaces, but can't mix the two. Pick one and stick with it; the convention is to indent with four spaces. Beyond that, it's mostly a matter of personal preference. When I was self learning (which isn't really fair because tons of people here helped me) I eventually got caught up trying to be perfect with convention. Turns out that's really not that important and I found a style that I like and use that. For pointers, you can look at PEP 8.

And just for fun, open up an Indigo Scripting Shell and run this code;
Code: Select all
import this

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Tue Oct 30, 2018 5:03 pm
teejay6 offline
Posts: 44
Joined: Jan 31, 2011
Location: Menlo Park, CA

Re: Python Script help

Thanks for the tip on this. I just used the same approach to add a Color Name Dictionary to the /Library/Python/2.7/site-packages to use for my Philips Hue bulb scripts.

Code: Select all
color_name_dict = {
   'Alice Blue' : "94,97,100",
   'Antique White' : "98,92,84",
   'Aqua' : "0,100,100",
   'Aquamarine' : "50,100,83",
    ...
   'Yellow' : "100,100,0",
   }


This dictionary allows me to refer to the colors in my scripts by the same names that Alexa recognizes. I have multiple color scripts, and now just have to put a one line import at the top
Code: Select all
from Color_Name_Dictionary_X11 import color_name_dict

I have a couple of questions:

1. Is /Library/Python/2.7/site-packages still the best directory to store external files for python scripts? I originally tried to specify the full path name in my import statement, but I couldn't get it to work:
Code: Select all
from /Users/tomj/Google Drive/Indigo/Python/Color_Name_Dictionary_X11 import color_name_dict

Script Error Color_Race_Random_Dictionary_Test-OFFICE_Halloween.py: invalid syntax
Script Error around line 4 - "from /Users/tomj/Google Drive/Indigo/Python/Color_Name_Dictionary_X11 import color_name_dict"



2. The dictionary I started with has 140 colors. There are other files with several thousand colors by name. Is it better to have one large file that includes several dictionaries, or separate files? Is there a performance hit for having large dictionaries?

Thanks

Posted on
Mon Nov 05, 2018 10:10 am
jay (support) offline
Site Admin
User avatar
Posts: 18219
Joined: Mar 19, 2008
Location: Austin, Texas

Re: Python Script help

1) Yes, that's still the best place to install shared modules/scripts. You can't specify paths the way you were attempting though you could dynamically add paths. But the easiest way is to just put them in the standard location.

2) A large dictionary will cause Python to use more memory, and might impact lookup performance. Give it a try and if it's acceptable to you then it should be fine.

Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Posted on
Wed Nov 07, 2018 4:32 pm
teejay6 offline
Posts: 44
Joined: Jan 31, 2011
Location: Menlo Park, CA

Re: Python Script help

Thanks!

Posted on
Tue Jan 14, 2020 4:14 pm
mgolden50 offline
User avatar
Posts: 259
Joined: Jan 29, 2007
Location: Chandler, AZ

Re: Python Script help

Hi,

I just moved indigo from one Mac drive to another. I copied the Perceptive Automation folder from the old drive to the new one.
But it seems that doing that did not bring along the external Python scripts from the old system.

Everything seemed to work until I noticed that when I executed an action that called an external python script the script did not execute.
but when I selected edit for the referenced script it opened BBEdit but the script it opened was the 7.3 version and when I selected run in the edit window..

What is the file path to where indigo stores external python scripts? I Cant't seem to find it.

Thanks,

Mike

Posted on
Wed Jan 15, 2020 7:44 am
DaveL17 offline
User avatar
Posts: 6753
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Python Script help

Indigo doesn't store external scripts per se, but rather you tell Indigo where you've already stored them. For example, I store my external scripts in a folder that's in my iCloud Documents folder. That way, I can easily edit them from any machine on my network, or on my phone when I'm away from home. When I upgrade versions of Indigo, I don't need to worry about them getting misplaced.

Try this:
Select a file to edit so that it opens up in BBEdit like you described, then [⌘-Click] on the file name at the top of the BBEdit window. That will show you the path to the file you're looking at.

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Wed Jan 15, 2020 10:21 am
mgolden50 offline
User avatar
Posts: 259
Joined: Jan 29, 2007
Location: Chandler, AZ

Re: Python Script help

Dave,

Thanks for for our support as usual.

Here is the path that BBEdit shows for a specific script:
/Volumes/Bentley-System-old/Users/bentley/.trash/Indigo 7.3/Scripts/Alexa Play Announcement In Variable To House.py

But when I enter this string into Go>Go To Folder in Finder it does not find the file. And I also can't seem to find the Scripts folder referenced in the path by searching the old drive. Not sure why.
I know that ".trashes" is a hidden folder but that's no helping me find it.

I suppose I can open each external script individually in BBEdit and then save them into a new folder on the new drive. But how do I find all of my external scripts--there are many.?

I don't remember specifying the path for these scripts when I converted them from AppleScripts. How does one do that?

Thanks again for your coaching,

Mike

Posted on
Wed Jan 15, 2020 1:41 pm
mgolden50 offline
User avatar
Posts: 259
Joined: Jan 29, 2007
Location: Chandler, AZ

Re: Python Script help

Hi Dave,

Please ignore my last request for help
I finally located the folder that contained the external scripts.
And I've now moved them to a new folder on the new drive.
Now I need to re-choose them from every action that uses them.

Thanks,

Mike

Posted on
Wed Jan 15, 2020 1:59 pm
DaveL17 offline
User avatar
Posts: 6753
Joined: Aug 20, 2013
Location: Chicago, IL, USA

Re: Python Script help

Glad you were able to find them. My recommendation would be to put them somewhere outside the Indigo folder tree so that their location becomes static.

I notice that the path you referenced above includes '.trash' which also is not recommended. :D

I came here to drink milk and kick ass....and I've just finished my milk.

[My Plugins] - [My Forums]

Posted on
Wed Jan 15, 2020 3:01 pm
mgolden50 offline
User avatar
Posts: 259
Joined: Jan 29, 2007
Location: Chandler, AZ

Re: Python Script help FCC

I didn’t put them in a .trash folder and have no idea how they got there.
I suspect that’s why they were so difficult to find.
When running Indigo on 7.3 on the old drive they were in a Scripts folder in Application Support>Perceptive Automation.

Posted on
Wed Jan 15, 2020 3:41 pm
jay (support) offline
Site Admin
User avatar
Posts: 18219
Joined: Mar 19, 2008
Location: Austin, Texas

Re: Python Script help FCC

mgolden50 wrote:
I didn’t put them in a .trash folder and have no idea how they got there.
I suspect that’s why they were so difficult to find.
When running Indigo on 7.3 on the old drive they were in a Scripts folder in Application Support>Perceptive Automation.


Based on the path, at some point the Indigo 7.3 folder was dragged into the trash in the Finder (when that disk was the startup disk I'd guess) but the trash was never emptied (good thing for you). That's where trashcan items reside (/Users/yourusername/.trash/) until you empty the trash.

Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 5 guests