User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 508
Joined: Sat Nov 02, 2013 2:06 pm

Python 2 and Python 3 Missing Module Issue

Sat Oct 14, 2017 8:07 am

Hi;

Someone on GitHub has helped me successfully play a video, pause it and play a second video and unpause the first using Will Price's OMXPlayer-Wrapper for omxplayer. What I want to do know is expand this code to add more videos for different scenarios as a front end to an interactive program for the children in my class (I am a teacher).

The original program works fine but as soon as I copy and edit it when I try and run it I get the "no module named keyb" error.

The working code has a python2 tag '#!/usr/bin/env python2 and I was opening and saving it using IDLE 3 thinking that this was causing the issue I then tried IDLE 2 and I have the exact same issue.

Here is the edited code - all I have changed is the name and location of the video 'Buddy/wait.m4v'.

Code: Select all

#!/usr/bin/env python2

# Modified jonnyalpha code by jehutting
# See jonnyalpha's code at will price python-omxplayer-wrapper issue #90
# Original code uses gpiozero's PIR in stead of keyboard keys.
# Removed also unused camera code.
# Makes use of user longagofaraway "Allow control of multiple instances via dbus #89"
# pull request!

import os
import sys
from time import sleep
from omxplayer import OMXPlayer
#from gpiozero import MotionSensor
from signal import pause

from keyb import KBHit
kb = KBHit()

videos = './'
adev='alsa'
vid1 = OMXPlayer(videos+'/Videos/Buddy/wait.m4v',args=['--no-osd', '--no-keys', '--win', '100 100 640 480', '--loop', '-o', adev], dbus_name='org.mpris.MediaPlayer2.omxplayer1', pause=True)

def main():
    try:  # was missing in original code
        initiate()
        print("playing vid1")
        vid1.play()

        while True:
            # keyboard PIR simulation
            if kb.kbhit():
                c = kb.getch()
                if c == chr(27) or c == 'q': # ESC or 'q' key to exit the program
                    print("terminated by user using ESC or 'q'")
                    break
                elif c == 'm': # key 'm' simulates the pir's when_motion callback 
                    motion_detected()
                # uncomment following code when vid1 is not to resume after vi2 completion
                # see motion_detected
                #elif c == 'n': # key 'n' simulates the pir's when_no_motion callback 
                #    no_motion()
            sleep(1)
    except KeyboardInterrupt:
        print("terminated by user using Ctrl+C")
    finally:
        vid1.quit()
        #vid2.quit()
    print("bye bye")

def initiate():
    print("CENTRAL AI Startup - Running initial setup")
    sleep(1)
    print("Starting Central AI visual front end")
    sleep(1)
    print("Motion detection activated")
    sleep(1)
    print("Security system activated")

def no_motion():
    print("All quiet")
    # comment following code when vid1 is to resume after vid2 completion
    # see motion_detected
    #print("Playing Vid_Wait_Loop")
    #vid1.play() # = un-pausing

def motion_detected():
    print("Intruder Detected")
    #sleep(2)
    print("Pausing loop")
    vid1.pause()
    print("Playing Vid_Name_Hammerstein")
    vid2 = OMXPlayer(videos+'/Videos/Vid_Name_Hammerstein.mp4',args=['--no-osd', '--no-keys', '--win', '100 100 640 480', '--layer', '10',
                     '-o', adev], dbus_name='org.mpris.MediaPlayer2.omxplayer2', pause=True)
    vid2.play_sync()
    # Once the playing of vid2 is finished (the real) OMXPlayer terminates.
    # Sending commands to vid2 will fail!
    # uncomment following code to resume playing vid1 after vid2 completion
    print("Playing Vid_Wait_Loop")
    vid1.play() # = un-pausing
    

if __name__ == '__main__': 
    main()

Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

DirkS
Posts: 7619
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: Python 2 and Python 3 Missing Module Issue

Sat Oct 14, 2017 9:25 am

Can't find any reference on the web re module keyb (that name is just too generic)
Did you download / install it or is it a self-made module?
If installed: did you install it for Python and 3?

B.Goode
Posts: 4601
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Python 2 and Python 3 Missing Module Issue

Sat Oct 14, 2017 9:54 am

The working code has a python2 tag '#!/usr/bin/env python2 and I was opening and saving it using IDLE 3 thinking that this was causing the issue I then tried IDLE 2 and I have the exact same issue.
The "shebang" line at the top of the script is an instruction to the shell about how to run the script if it is invoked directly from the shell, for instance as ./myscript

If you run the script explicitly via Python(2) or IDLE, or via Python3 or IDLE3, the shebang line has no effect and the script is run by whichever python interpreter you chose to run it with.

The underlying root cause seems to be the availability of that keyb module. You say
The original program works fine
Does it still work fine? Are the original and modified versions running from the same working directory in similar circumstances?

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 508
Joined: Sat Nov 02, 2013 2:06 pm

Re: Python 2 and Python 3 Missing Module Issue

Mon Oct 16, 2017 8:08 pm

Sorry guys I have been sending you on a goose hunt :-(
I just looked at this again and noticed a program in the main folder (pi) called keyb.py. So much has happened since I last looked at this the module must have been this custom one written / modified by Jozef Hutting - the gentleman who helped me out.
I am going to dump this in the folder where I have modified my code and see if it works?

I'll post back.

Here is the keyb module:

Code: Select all

#!/usr/bin/env python
'''

A Python class implementing KBHIT, the standard keyboard-interrupt poller.
Works transparently on Windows and Posix (Linux, Mac OS X).  Doesn't work
with IDLE.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as 
published by the Free Software Foundation, either version 3 of the 
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

'''

'''
From http://stackoverflow.com/questions/2408560/python-nonblocking-console-input
Modified: 30-12-2016 Jozef Hutting <jehutting@gmail.com>

'''

import os

# Windows
if os.name == 'nt':
    import msvcrt

# Posix (Linux, OS X)
else:
    import sys
    import termios
    import atexit
    from select import select


class KBHit:

    def __init__(self):
        '''Creates a KBHit object that you can call to do various keyboard things.
        '''

        if os.name == 'nt':
            pass

        else:

            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

            # Support normal-terminal reset at exit
            atexit.register(self.set_normal_term)


    def set_normal_term(self):
        ''' Resets to normal terminal. On Windows this is a no-op.
        '''

        if os.name == 'nt':
            pass

        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)


    def getch(self):
        ''' Returns a keyboard character after kbhit() has been called.
            Should not be called in the same program as getarrow().
        '''

        s = ''

        if os.name == 'nt':
            return msvcrt.getch().decode('utf-8')

        else:
            return sys.stdin.read(1)


#    def getarrow(self):
#        ''' Returns an arrow-key code after kbhit() has been called. Codes are
#        0 : up
#        1 : right
#        2 : down
#        3 : left
#        Should not be called in the same program as getch().
#        '''
#
#        if os.name == 'nt':
#            msvcrt.getch() # skip 0xE0
#            c = msvcrt.getch()
#            vals = [72, 77, 80, 75]
#
#        else:
#            c = sys.stdin.read(3)[2]
#            vals = [65, 67, 66, 68]
#
#        return vals.index(ord(c.decode('utf-8')))


    def kbhit(self):
        ''' Returns True if keyboard character was hit, False otherwise.
        '''
        if os.name == 'nt':
            return msvcrt.kbhit()

        else:
            dr,dw,de = select([sys.stdin], [], [], 0)
            return dr != []


# Test    
if __name__ == "__main__":

    kb = KBHit()

    print('Hit any key, or ESC to exit')

    while True:

        if kb.kbhit():
            c = kb.getch()
            if ord(c) == 27: # ESC
                break
            print(c)

    kb.set_normal_term()

Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

jehutting
Posts: 135
Joined: Sun Feb 15, 2015 8:37 am
Location: The Netherlands

Re: Python 2 and Python 3 Missing Module Issue

Tue Oct 17, 2017 7:07 am

Good to see that you found the missing module. I added the keyb module to your project as a replacement/simulation of your PIR sensor :-)

Notice the remark at the top of the keyb module that it doesn't work in Idle.

Yes keep us/me posted about your project.

Just have fun with Mr. Hammerstein!!!

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 508
Joined: Sat Nov 02, 2013 2:06 pm

Re: Python 2 and Python 3 Missing Module Issue

Tue Oct 17, 2017 7:55 pm

Ah Mr Hutting, I have been searching for your contact details to help out with this and could not find them until I spotted the module :-)

I am working on two projects for which I need python-omxplayer-wrapper, one is the code that you originally helped me with for a static virtual robot and the other is a schools based programming project for my British Computer Society certifcate in teaching computing. The first project as you know uses a PIR sensor but the second project relies on user keyboard interaction so the keyb module is brilliant.

I have been working on the second project and now that I realise that I need the keyb module in the same directory as the program I no longer get the error. I have managed to get the program to run without any syntax or module errors but I have run into a problem. Both programs have the same code at the start to play a looping video before reacting to a user key press. Whilst the first one (that you modified) works fine the second does not.

The video plays immediately (known open issue with python-omxplayer-wrapper) but the print statements are not displayed - the terminal just freezes up and the program cannot be terminated.

I was just about to copy the code to show you but for some reason all of my changes that I made last night have now disappeared!! This happened the night before - I thought I was going crazy but a quick search of the Internet reveals that people have experienced this before SD cards suddenly becoming read only - bizzare!!

New SD Card then!!!
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

jehutting
Posts: 135
Joined: Sun Feb 15, 2015 8:37 am
Location: The Netherlands

Re: Python 2 and Python 3 Missing Module Issue

Wed Oct 18, 2017 6:32 am

It's all to you how you contact me: through this forum PM, Github PM or direct using my gmail account :D

For issues with Will Price's python-omxplayer-wrapper better use its Github Issues facility which forms a better archive and search for issues with the wrapper.

I will be glad to help you (and of course, others too ;) )

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 508
Joined: Sat Nov 02, 2013 2:06 pm

Re: Python 2 and Python 3 Missing Module Issue

Sat Oct 21, 2017 3:53 pm

Ok so I am now making some progree (my current script now has three different videos!!!) and appears to be working OK.

It is written in Python 2 however, which has caused me some trouble especially when trying to get user input, I instinctively used:

Code: Select all

name = input("what is your name")
The above code is python 3 and it took me a while to find out the python 2 version:

Code: Select all

name = str(raw_input("what is your name")
Is omxplayer-wrapper now working with python3?
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

jehutting
Posts: 135
Joined: Sun Feb 15, 2015 8:37 am
Location: The Netherlands

Re: Python 2 and Python 3 Missing Module Issue

Sun Oct 22, 2017 6:04 am

AFAIK the wrapper works with python2 and python3.

I thought that Python2 raw_input() always returns a str type...so surprised you needed the casting.

Return to “Python”

Who is online

Users browsing this forum: elParaguayo and 19 guests