-1

I am running a python file at command prompt and it is working fine. Execution of the file as

python myfile.py -d device01 -s on and this is working. when I import the same class from another file, it's not working.

Source code:

#!/usr/bin/env python3

import pytuya
import sys
import getopt
import json

def smartlite(argv):

    device = ''
    state = ''
    try:
        opts, args = getopt.getopt(argv,"hd:s:",["help", "device=", "state="])
    except getopt.GetoptError:
        print (sys.argv[0], '-d <device> -s <state>')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print (sys.argv[0], '-d <device> -s <state>')
            sys.exit()
        elif opt in ("-d", "--device"):
            device = arg
        elif opt in ("-s", "--state"):
            state = arg

    filename = "p.json"
    if filename:
        with open(filename, 'r') as f:
            datafile = json.load(f)

    print ('Device is', device)
    print ('State is', state)
    print (datafile["devices"][device]["uuid"])
    print (datafile["devices"][device]["key"])
    print (datafile["devices"][device]["ip"])

    d = pytuya.OutletDevice(datafile["devices"][device]["uuid"], datafile["devices"][device]["ip"], datafile["devices"][device]["key"])
    data = d.status()  # NOTE this does NOT require a valid key
    print('Dictionary %r' % data)
    print('state (bool, true is ON) %r' % data['dps']['1'])  # Show status of first controlled switch on device

    # Toggle switch state
    switch_state = data['dps']['1']
    data = d.set_status(not switch_state)  # This requires a valid key
    if data:
        print('set_status() result %r' % data)

    sys.exit(0)


if __name__ == "__main__":
   smartlite(sys.argv[1:])

The above code is working when I run at command prompt as

\.> python myfile.py -d device01 -s on

when I am calling the above code from another file I am getting an error.

Importing the library of smartlite.

from sourcefolder.pytuya import smartlite # this is good.
try:
        smartlite.get("-d Lite01 -s on")
            #os.system('python pytuya/mypytuya.py -d Lite01 -s on')

    except sr.UnknownValueError:
        print('error')
    except sr.RequestError as e:
        print('faile'.format(e))

error when executing.

('Device is', '')
('State is', '')
Traceback (most recent call last):
  File "voicetotext.py", line 22, in <module>
    smartlite("-d Lite01 -s on")
  File "/home/respeaker/voice-engine/examples/pytuya/mypytuya.py", line 34, in smartlite
    print (datafile["devices"][device]["uuid"])
KeyError: ''
Melebius
  • 6,183
  • 4
  • 39
  • 52
  • 1
    Please put the code and data in your question **here**, not as link to off-site locations. – martineau May 22 '20 at 18:24
  • what error are you getting? – DrBwts May 22 '20 at 18:32
  • Are you trying to pass command line arguments as parameters to a function? – Guy Incognito May 22 '20 at 18:32
  • you maybe should add directory to sys path like this: https://stackoverflow.com/questions/16114391/adding-directory-to-sys-path-pythonpath – M.qaemi Qaemi May 22 '20 at 18:34
  • Well, `if a=b` is a syntax error as well as `smartlite(-d device01 -s on)` –  May 22 '20 at 18:53
  • You are specifying the input file `p.json` without a path. Are you sure the file is available in the working directory and contains the expected data in your latter example? – Melebius May 25 '20 at 11:42
  • Does this answer your question? [How to read a file in other directory in python](https://stackoverflow.com/questions/13223737/how-to-read-a-file-in-other-directory-in-python) – Melebius May 25 '20 at 11:45
  • when I am running the code at command prompt, it works: python myfile.py -d device01 -s on How to send the same parameter when I am calling the function like smartlite(-d device01 -s on) – user13597916 May 26 '20 at 12:46
  • There is no problem with p.json. only problem when I am calling the smartlite function from other python script I am not able to send arg ments. When I run the file individually it works like this /.>python myfile.py -d Lite01 -s on – user13597916 May 26 '20 at 17:03

2 Answers2

0

Thank you guys this conversation helped me.

I am able to send the arguments now to the fuction in this format and it got worked.

if a=b: smartlite(['-d','device01','-s','on'])

-1

You have several options:

(a) Edit your .bashrc, add something like:

export PYTHONPATH="$HOME/dir-base-sourcefolder"

(b) Review the directory structure. Check the relative depth from the module and the caller. Try with:

from .sourcefolder.pytuya import smartlite
from ..sourcefolder.pytuya import smartlite
Omr
  • 39
  • 4
  • Could you post your dir structure? (I'm new on SO, sorry this options did work for you) – Omr May 22 '20 at 19:37
  • when I am running the code at command prompt, it works: python myfile.py -d device01 -s on How to send the same parameter when I am calling the function like smartlite(-d Lite01 -s on) – user13597916 May 26 '20 at 12:46
  • Now that there is more context, and as at first glance, I'll suggest you to debug `device` in particular seems that `elif opt in ("-d", "--device"): device = arg` is assigning `device = ''` so you are getting `KeyError: ''`. As a good practice I suggest to split your function in 3 functions to achieve https://en.wikipedia.org/wiki/Separation_of_concerns and in particular https://en.wikipedia.org/wiki/Loose_coupling. (BTW, I did not downvoted your question) – Omr May 26 '20 at 13:33
  • its working now, I am able to send the args now to a function. – user13597916 May 26 '20 at 17:29