Python Script help

Posted on
Sat Nov 12, 2016 7:17 pm
dz1rfj offline
Posts: 114
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"



Posted on
Thu Nov 17, 2016 7:34 pm
dz1rfj offline
Posts: 114
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!

Posted on
Thu Nov 17, 2016 9:03 pm
DaveL17 offline
User avatar
Posts: 4849
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: 4849
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: 35
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: 15477
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: 35
Joined: Jan 31, 2011
Location: Menlo Park, CA

Re: Python Script help

Thanks!

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 1 guest