Python function stops working after moving it to another file - python

I have a python code that works how I expect it to, and I want to move the functions send_cmd() to another commands.py file.
import add_pinout
from lib import *
pinout = {}
avr_board = AVRClient('COM3', 250000)
i2c_master = I2CMaster(avr_board)
i2c_slave_adress = 0x1E
i2c_device = I2CDevice(avr_board, i2c_slave_adress)
def send_cmd(cmd):
try:
if cmd[0][:4] == 'LCL_':
if cmd[0] == 'LCL_ALL':
for pin in pinout:
gpio_pin = GPIO(avr_board, pinout[pin], GPIO.Mode.OUTPUT)
if cmd[1] is '1': gpio_pin.write(True)
elif cmd[1] is '0': gpio_pin.write(False)
else:
gpio_pin = GPIO(avr_board, pinout[cmd[1]], GPIO.Mode.OUTPUT)
if cmd[1] is '1': gpio_pin.write(True)
elif cmd[1] is '0': gpio_pin.write(False)
elif cmd[0] == 'WRITE':
i2c_device.data_transfer(cmd[1], len(cmd[1]))
elif cmd[0] == 'READ':
print i2c_device.data_transfer([], len('1010'))
elif cmd[0] == 'WRITE+READ':
print i2c_device.data_transfer(cmd[1], len('1010'))
else:
print 'Something went wrong...'
except KeyError:
print 'Such pin does not exist.'
except IndexError:
print 'Not enough arguments.'
if __name__ == "__main__":
pinout.update(add_pinout.read_pins())
print(pinout)
while(True):
send_cmd(raw_input().split())
I do it by adding from commands.py import send_cmd and addiing arguments to the function. The call looks like this: send_cmd(avr_board, pinout, i2c_device, raw_input().split()), while the declaration in commands.py is def send_cmd(avr_board, pinout, i2c_device, cmd):. When i run the code it accepts user input, but when it calls start_cmd from commands.py, it just goes to the else clause, like it couldnt see the list made by raw_input().split().
Edit
I have found the error - in commands.py I have changed == into is in each if statement. I have reversed this change and now everything's fine.

Related

def() function screws with my indentation

I'm writing a basic script that scans files and moves them if they fit some criteria set by the user.
I have tried complying with what it wants but that just ends up with every line of code being indented one more than the other.
def check():
#code simplication
for i in range(2):
if fileScanDestination == '':
noValue(moveFrom)
else:
#exits
if fileMoveDestination == '':
noValue(moveTo)
else:
#exits
if specialFileExtension == '':
str(specialFileExtension) == 'nil'
else:
#exits
if fileNameSpecial == '':
str(fileNameSpecial) == str('nil')
else:
#exits
def p(text):
print(text)
#setting up tkinter
# getting variable data
p('Please enter the path for the files you would like to sort.')
fileScanDestination == str(input())
This should just have to be indented once, then exit. But since it wants to indent every new line, which just looks bad.
Try putting some pass instructions after the else statements, or some return's if you say it should exit.
You could even shorten the whole thing by doing:
if any([
fileScanDestination == '',
fileMoveDestination == '',
specialFileExtension == '',
str(specialFileExtension) == 'nil',
str(fileNameSpecial) == str('nil'),
fileNameSpecial == ''
]):
return

How to continue the program even after evaluating the condition to true in if else loop in python?

I am implementing the scenario in which i have multiple if,elif,else loops.My problem is when the condition met ,its coming out of the program and exits the program .
Expected Behavior - After successful completion it should not exit but rather again show me the options to select .Only after pressing something like cntrl+c it should exit out the program.
class Manager:
def __init__(self):
self.not_useful_tests = []
self.sdsf
def sdsf(self):
try:
input = raw_input()
if input == 'x':
self.not_useful_tests.append(0)
else:
if input == 1:
verify = self.ABC()
return verify
if input == 2:
verify = self.xyz()
return verify
if input == 3:
verify = self.hyg()
return verify
if input == 4:
verify = self.fgh()
return verify
if input == 5:
verify = self.qwe()
return verify
except KeyboardInterrupt as e:
print "Exception caught : " + str(e)
return None
How to achieve this beahvior ? What to add in the code so as to achieve the task ?
To repeat something while some condition is true, use a while loop:
while True:
input = raw_input()
if input == 1:
return 'some value'
if input == 2:
return 'some other value'
If you don't want to return a function result, but rather want to continue execution outside of the loop, i.e. 'break out of the loop' use break:
while True:
input = raw_input()
if input == 1
print('doing something')
break
if input == 2
print('doing something else')
break
print('Continuing here')
And if that's what you want, you can also set a condition to end the loop like this:
result = None
while result is None:
input = raw_input()
if input == 1:
result = 'x'
if input == 2:
result = 'y'
print('will continue here if result has a value')

NameError: name 'form' is not defined (Python3)

Basically the main method takes user input, checks it and calls the first method if the user doesn't enter quit.
The first method checks the first section of the input and calls one of the other methods depending on what the user enters. This is the point I get an error; when the first method calls the form method, for example, I get an NameError: name 'form' is not defined exception. I'm a little confused about this since I've defined each method and they're all spelt correctly, also when I call the quit method it works perfectly fine.
Main method:
if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) == "quit"): quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2): first(a)
elif (len(a) is 3): first(a)
else: print("Invalid Input. Please Re-enter.")
First method:
def first(a = list()):
word = a[0]
if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Other methods (these are all called from the first method):
def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format " + one)
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
this error is because of
elif word == "format":
form(a[1])
python basically doesn't know what form is.
let me show you:
gaf#$[09:21:56]~> python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> form()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'form' is not defined
>>>
there is two ways out
>>> def form():
... pass
...
>>> form()
>>> form
<function form at 0x7f49d7f38a28>
>>>
or import it form some library using
import
command
also order is matters too
try:
form()
except NameError:
print('Oops name error raise above')
def form():
print('form foo is called')
try:
form()
except NameError:
print('Oops name error raise below')
will give you
/home/gaf/dashboard/bin/python /home/gaf/PycharmProjects/dashboard/test.py
Oops name error raise above
form foo is called
Process finished with exit code 0
P.S.
take a look at pep8
your code is a mess %)
but no worries this what everybody does with first language
It depends if you use python 2.7 or 3, but your code works with some minor changes.
import sys
def reconnect(one=""):
print("Reconnect")
def ls(one=""):
print("list")
def mkfile(one=""):
print("make file")
def mkdir(one=""):
print("make drive")
def append(one="", two=""):
print("append")
def form(one=""):
print("format " + one)
def delfile(one=""):
print("delete file")
def deldir(one=""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
def first(a=list()):
word = a[0]
if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
line = raw_input("Some input please: ") # or `input("Some...` in python 3
print(line)
s = line.strip()
if (str(s) == "quit"):
quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2):
first(a)
elif (len(a) is 3):
first(a)
else:
print("Invalid Input. Please Re-enter.")
Test
python pyprog.py
Some input please: ls text.txt
ls text.txt
['ls', 'text.txt']
list
You can also try it online.

"list index out of range" exception (Python3)

I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the if or elif part of the second if statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.
if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) is "quit") == True: quit()
elif (str(s) is "quit") == False:
a = s.split()
print(a)
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
else: print("Invalid Input. Please Re-enter.")
The first method is: (The methods it calls in the if statement just print things out at the moment)
def first(self, a = list()):
word = a[0]
if word is ls:
ls(a[1])
elif word is format:
form(a[1]) # EDIT: was format
elif word is reconnect:
reconnect(a[1])
elif word is mkfile:
mkfile(a[1])
elif word is mkdir:
mkdir(a[1])
elif word is append:
append(a[1], a[2])
elif word is delfile:
delfile(a[1])
elif word is deldir:
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Other methods:
def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format")
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
The problem seems to be the definition of first(). You invoke it as a function:
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
But you define it as a method:
def first(self, a = list()):
The array of command and argument gets put into self and a is always an empty list which you attempt to index and fail. Also, you shouldn't use a mutable type like list() as a default value unless you're certain what you are doing. I suggest simply:
def first(a):
As far as your __main__ code goes, simplify:
if __name__ == '__main__':
for line in sys.stdin:
string = line.strip()
if not string:
break
if string == "quit":
quit()
tokens = string.split()
length = len(tokens)
if 2 <= length <= 3:
first(tokens)
else:
print("Invalid Input. Please Re-enter.")
Real issue:
To solve your error you have to remove the self parameter of the first function
def first(a=list())
Basically the self is only used for object orientation creating methods.
Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to.
My second issue I can point out is that, You are trying to compare using is between a string and a function.
def first(a = list()):
word = a[0]
if word is "ls":
ls(a[1])
elif word is "format":
format(a[1])
elif word is "reconnect":
reconnect(a[1])
elif word is "mkfile":
mkfile(a[1])
elif word is "mkdir":
mkdir(a[1])
elif word is "append":
append(a[1], a[2])
elif word is "delfile":
delfile(a[1])
elif word is "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Extra
The is function on built in operations in Python. is compare the equity of the objects.
But this expression:
if (str(s) is "quit") == True:
Can be simpler like:
if str(s) == "quit":
Or:
if str(s) is "quit":
The == True is meaningless either == False you can use not more pythonicly.

Revisiting Functions In Python 3

In my script I have four functions that work like this:
def function_four():
# Does Stuff
function_one()
def function_three():
# Does Stuff
function_two()
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
function_three()
elif usr_input == '2':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
function_four()
elif usr_input == '2':
function_three()
elif usr_input == '3':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
I need to know if this will cause the problem I think it will: the functions never closing, causing lots of open functions (and, presumably, wasted memory and eventual slow-down) to appear, never to disappear until the user quits the script. If true, then this would most likely be bad practise and inadvisable, meaning that there must be an alternative?
Whenever you have Python code that is:
Recalling The Same Function So That If The User Does Not Chose One Of The Other Statements Then They Can Try Again Rather Than The Program To Stop Working,
you are almost always better off replacing the recursive call with a loop. In this case the recursion is completely unnecessary, probably wastes resources and arguably makes the code harder to follow.
edit: Now that you've posted the code, I'd suggest recasting it as a state machine. The following page provides a summary of Python modules that could be useful: link.
Even without any additional modules, your code lends itself to a simple non-recursive rewrite:
import sys
def function_four():
# Does Stuff
return function_one
def function_three():
# Does Stuff
return function_two
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
return function_three
elif usr_input == '2':
return None
else:
print("Did not recognise command. Try again.")
return function_one
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
return function_four
elif usr_input == '2':
return function_three
elif usr_input == '3':
return None
else:
print("Did not recognise command. Try again.")
return function_two
state = function_one
while state is not None:
state = state()
Note that the functions no longer call each other. Instead, each of them returns the next function to call, and the top-level loop takes care of the calling.

Categories