DECRBY in Redis not working in Python code - python-2.7

I am using redis in my Python code to store keys, however there the Python code wasn't running as it was supposed to. I haven't found any errors in my code, so I started turning things into comments and I found that the redis command DECRBY doesn't seem to work.
I have tried all the various commands such as INCR, INCRBY, and DECR and those work. But DECRBY isn't acting as expected (even though it is the same syntax as INCRBY and that works).
elif (text == "test1"):
r.incr(count)
send_message(sender_id, r.get(count))
elif (text == "test2"):
r.incrby(count,10)
send_message(sender_id, r.get(count))
elif (text == "test3"):
r.decr(count)
send_message(sender_id, r.get(count))
elif (text == "test4"):
r.decrby(count,10)
send_message(sender_id, r.get(count))
My program sends a message through Facebook regarding the result. I have the code in a try statement and an exception that sends a message that says "Exception".
I have initialized the count to 8, and as you can see here:
https://imgur.com/a/bSipS3Q .
It throws the exception for test4 which is DECRBY.
I have tried the commands in the Redis CLI, and DECRBY works in the command line, but not when from the python program.
The workaround I am using right now is the INCRBY method by the negative of the value I want to decrease.
Is there a reason why the DECRBY wouldn't work? I can't figure out why r.incrby works, but changing it to r.decrby leaving everything else constant doesn't. Is there a way to debug this?

Related

Receiving back string of lenght 0 from os.popen('cmd').read()

I am working with a command line tool called 'ideviceinfo' (see https://github.com/libimobiledevice) to help me to quickly get back serial, IMEI and battery health information from the iOS device I work with daily. It executes much quicker than Apple's own 'cfgutil' tools.
Up to know I have been able to develop a more complicated script than the one shown below in PyCharm (my main IDE) to assign specific values etc to individual variables and then to use something like to pyclip and pyautogui to help automatically paste these into the fields of the database app we work with. I have also been able to use the simplified version of the script both in Mac OS X terminal and in the python shell without any hiccups.
I am looking to use AppleScript to help make running the script as easy as possible.
When I try to use Applescript's "do shell script 'python script.py'" I just get back a string of lenght zero when I call 'ideviceinfo'. The exact same thing happens when I try to build an Automator app with a 'Run Shell Script' component for "python script.py".
I have tried my best to isolate the problem down. When other more basic commands such as 'date' are called within the script they return valid strings.
#!/usr/bin/python
import os
ideviceinfoOutput = os.popen('ideviceinfo').read()
print ideviceinfoOutput
print len (ideviceinfoOutput)
boringExample = os.popen('date').read()
print boringExample
print len (boringExample)
I am running Mac OS X 10.11 and am on Python 2.7
Thanks.
I think I've managed to fix it on my own. I just need to be far more explicit about where the 'ideviceinfo' binary (I hope that's the correct term) was stored on the computer.
Changed one line of code to
ideviceinfoOutput = os.popen('/usr/local/bin/ideviceinfo').read()
and all seems to be OK again.

Debuggers not acting properly on Jupyter notebooks

I'm trying to debug some code in a Jupyter notebook. I've tried 3 4 different methods, and they all suffer from the same problem:
--Return--
None
> <ipython-input-22-04c6f5c205d1>(3)<module>()
1 import IPython.core.debugger as dbg
2 dber = dbg.Tracer()
----> 3 dber()
4 tst = huh.plot(ret_params=True)
5 type(tst)
ipdb> n
> y:\miniconda\lib\site-packages\ipython\core\interactiveshell.py(2884)run_code()
2882 finally:
2883 # Reset our crash handler in place
-> 2884 sys.excepthook = old_excepthook
2885 except SystemExit as e:
2886 if result is not None:
as you can see, the n command, which from what I understood from the pdb documentation should execute the next line (I'm assuming ipdb is just pdb adapted to work on IPython, especially since I can't find any command documentation that refers specifically to ipdb and not pdb)
s also has the same problem. This is actually what I want to do - step into the plot call (from what I understand, this is what s is supposed to do), but what I get is exactly the same as what I get from n. I also just tried r and I get the same problem.
Every example I've seen just uses Tracer()() or IPython.core.debugger.PDB().set_trace() to set a breakpoint in the line that follows the command, but both cause the same problems (and, I assume, are actually the exact same thing).
I also tried %debug (MultipleInstanceError) and %%debug (Doesn't show the code in the line being executed - just says what line, using s doesn't step into the function, just runs the line).
Edit: turns out, according to a blog post from April of this year, plain pdb should also work. It does allow me to interactively debug the notebook, but it only prints the current line being debugged (probably not a bug), and it has the same problem as IPython's set_trace() and Tracer()()
on plain IPython console, IPython's set_trace (only one I've tested) works just fine.
I encountered the same problem when debugging in Jupyter Notebook. What is working for me however, is when I call set_trace() inside a function. Why is explained here (click), though I don't really understand why others don't encounter this problem. Anyway, if you need a pragmatic solution for your problem and you want to debug a self-written function, try this:
from IPython.core.debugger import set_trace
def thisfunction(x):
set_trace() # start debugging when calling the function
x += 2
return x
thisfunction(5) # ipdb console opens and I can use 'n'
Now I can use 'n' and the debugging process runs the next line without problems. If I use the following code, however, I run into your above mentioned problem.
from IPython.core.debugger import set_trace
def thisfunction(x):
x += 2
return x
set_trace() # start debugging before calling the function.
# Calling 's' in the ipdb console to step inside "thisfunction" produces an error
thisfunction(5)
Hope this helps until somebody could solve the problem completely.

subprocess.popen stream handling

Is it possible to prevent subprocess.popen from showing prompts in the terminal?
Attempting to map a drive but would like to read the prompt for credentials in the script rather than display them to the terminal. The idea being I can carry out actions based on the response.
I am aware the use of shell is frowned upon when using string based commands (for obvious reasons), however I'm controlling the input so am happy with the risk for testing purposes.
I was under the impression that all stdout (interaction) would be parsed into the output_null variable. Instead I am still getting the prompt in the terminal (as illustrated below). I'm either miss understanding how the streams work or I'm missing something. Can anyone enlighten me please
command = "mount -t smbfs //{s}/SYSVOL {m}".format(s=server, m=temp_dir)
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output_null = p.communicate()[0]
if "Password for" in output_null:
print 'awdaa'
Terminal Shows
Password for 192.168.1.111:

Reliably write and read to serial using python

I am communicating with a Fona 808 module from a Raspberry Pi and I can issue AT commands, yey!
Now I want to make a python program where I can reliably issue AT commands using shortcut commands like "b" for getting the battery level and so on.
This is what I have so far:
import serial
con = serial.Serial('/dev/ttyAMA0',timeout=0.2,baudraute=115200)
def sendAtCommand(command):
if command == 'b':
con.write("at+cbc\n".encode())
reply = ''
while con.inWaiting():
reply = reply + con.read(1)
return reply
while True:
x = raw_input("At command: ")
if x.strip() == 'q':
break
reply = sendAtCommand(x)
print(reply)
con.close()
In the sendAtCommand I will have a bunch of if statements that send different at commands depending on the input it receives.
This is somewhat working but is very unreliable. Sometimes I get the full message. Other times I get nothing. Then double message next time and so on.
I would like to create one method that issues a command to the Fona module and then reads the full response and returns it.
Any suggestions?
Your loop quits if the 'modem' has not responded anything to your at command yet. You should keep reading the serial input until you get a linefeed or until a certain time has passes e.g. 1 second or so.
Okay. It turns out this is pretty trivial.
Since at commands always return OK after a successful query then it is simply a matter of reading the lines until eventually one of them will contain 'OK\r\n'.
Like so:
def readUntilOK():
reply=''
while True:
x = con.readline()
reply += x
if x == 'OK\r\n':
return reply
This does not have a timeout and it does not check for anything else than an OK response. Which makes it very limiting. Adding error handling is up to the reader. Something like if x == 'ERROR\r\n' would be a good start.
Cheers!

GDB python script for bounded instruction tracing

I'm trying to write a GDB script to do instruction tracing in a bounded maner (i.e start addr and stop addr). Perhaps I'm failing at google but I cant seem to find this in existence already.
Here is my stab at it:
python
def start_logging():
gdb.execute("set logging on")
gdb.execute("while $eip != 0xBA10012E9")
gdb.execute("x/1i $eip")
gdb.execute("stepi")
gdb.execute(" end")
gdb.execute("set logging off")
gdb.execute("set pagination off")
gdb.execute("break *0xBA19912CF")
gdb.execute("command 1 $(start_logging())")
gdb.execute("continue")
In my mind this should set up a breakpoint then set the command to run when it hits. When the breakpoint hits it should single step through the code until the end address is hit and then it will turn off logging.
When I run this with gdb the application will break at the correct point but no commands are run.
What am I doing wrong? Sorry if this is the wrong way to go about this please let me know. I'm new to gdb scripting
I see a few odd things in here.
First, it looks like you are trying to split multi-line gdb commands across multiple calls to gdb.execute. I don't believe this will work. Certainly it isn't intended to work.
Second, there's no reason to try to do a "while" loop via gdb.execute. It's better to just do it directly in Python.
Third, I think the "command" line seems pretty wrong as well. I don't really get what it is trying to do, I guess call start_logging when the breakpoint is hit? And then continue? Well, it won't work as written.
What I would suggest is something like:
gdb.execute('break ...')
gdb.execute('run')
while gdb.parse_and_eval('$eip') != 0x...:
gdb.execute('stepi')
If you really want logging, either do the 'set logging' business or just instruct gdb.execute to return a string and log it from Python.