With gdb python scripting, I can have a helper function throw an error for an unexpected condition:
def isFOOEnabled( ):
sb = gdb.parse_and_eval( "foo" )
if sb == 0x0:
raise gdb.GdbError( "Fatal error." )
return sb
I can catch the expression not evaluated error in lldb python like so:
def isFOOEnabled( ):
sb = lldb.frame.EvaluateExpression( "foo" )
if sb.GetValue() is None:
return 0
return sb
but I'd also like to force the script to abort like in my gdb version.
For exposition, here is an example of a call to gdb.GdbError:
(gdb) info zregisters
Traceback (most recent call last):
File "/home/pjoot/gdb/zinfo.py", line 157, in invoke
isFOOEnabled( )
File "/home/pjoot/gdb/apis/common.py", line 24, in isFOOEnabled
sb = gdb.parse_and_eval( "sysblk" )
gdb.error: No symbol "sysblk" in current context.
Error occurred in Python command: No symbol "sysblk" in current context.
(gdb)
after which you are back to the (gdb) shell, with a python stacktrace so that you know where things went wrong. Looks like the string parameter that gdb.GdbError takes is actually lost.
Is there a python lldb.* helper function to do that like gdb.GdbError()?
Related
I run my bash script my_file.sh in a python file as follows:
import subprocess
def rest_api():
params = {
'query': 'indepedence day',
'formats': '["NEWSPAPER"]',
}
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
f'LANGUAGE={params.get("lang")}', # returns None!
])
if __name__ == '__main__':
rest_api()
Several of my input arguments in subprocess.call do not normally exist in a dictionary params={} (here I provided f'LANGUAGE={params.get("lang")}' as one example). I handle such unavailability in my_file.sh to initialize with something, for instance:
if [ -z "$LANGUAGE" ]; then LANGUAGE="${LANGUAGE:-[]}"; fi
What I want is to apply some sort of if else statement in subprocess.call function with this logic:
if params.get("lang") is None, do not even send it as an input to bash file, e.g., treat it as I never provided such input for my_file.sh.
Therefore, I tried to rewrote my code like this:
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
if params.get("lang"): f'LANGUAGE={params.get("lang")}', # syntax Error
])
which is wrong I get the following invalid syntax error:
Traceback (most recent call last):
File "nationalbiblioteket_logs.py", line 13, in <module>
from url_scraping import *
File "/home/xenial/WS_Farid/DARIAH-FI/url_scraping.py", line 17, in <module>
from utils import *
File "/home/xenial/WS_Farid/DARIAH-FI/utils.py", line 53
if params.get("lang"): f'LANGUAGE={params.get("lang")}',
^
SyntaxError: invalid syntax
Do I have a wrong understanding of applying if else statement for the input arguments of a python function or is there an easier or cleaner way doing it?
Cheers,
You can specify the default when calling .get(), so use an empty string.
f'LANGUAGE={params.get("lang", "")}'
If you don't want the LANGUAGE= argument at all when no value is provided, you need to build the list dynamically.
cmd = ['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}']
if (lang := params.get("lang")) is not None:
cmd += [f'LANGUAGE={lang}']
subprocess.call(cmd)
I'm getting an error when I run a script from the Linux command prompt(bash), but when I run the same script in the Pycharm directly, it works fine.
Here is the code:
class EncodeKey:
def __new__(cls, *args):
if len(args) == 1:
return cls.generate_encode_key(args[0].upper())
return cls.get_encode_key(args)
...
...
if __name__ == '__main__':
encode_key = EncodeKey(*["something"])
print(encode_key)
As I already told, in the Pycharm the script works fine without any errors, but here is what I'm getting when the script is run from the command prompt:
user#machine:~/my/path/to/the/script$ python py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Or:
user#machine:~/my/path/to/the/script$ ls -lh
...
-rwxrwxr-x 1 user user 3.2K Jun 20 19:12 py.py
...
user#machine:~/my/path/to/the/script$ ./py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Of, course, I didn't find any solutions on such an unusual problem. Any ideas why is that happening ? And how to solve it ? Thanks !
If you've installed python in the default way, the python command uses Python 2. To interperet with Python 3, use the command python3:
user#machine:~/my/path/to/the/script$ python3 py.py
The program errors in Python 2 because old-style classes, the default in Python 2, do not support __new__. If you need to support Python 2, make your class new-style by extending object:
class EncodeKey(object):
Your code will still work in Python 3 if you do this.
So every time I try to run the app I get "RuntimeError: generator raised StopIteration error". I am using Python 3.7 (btw I don't know how to type fancy in this so its nice to see)
I have tried changing utils.py
yield next(seq) to
try:
yield next(seq)
except StopIteration:
return
but that didn't seem to work. I've also re installed webpy but it didn't work.
import web
urls = (
'/(.*)', 'Hello'
)
app = web.application(urls, globals())
class Hello:
def GET(self, name):
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
This error pops up:
Traceback (most recent call last):
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\utils.py", line 526, in take
yield next(seq)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/Korisnik/Desktop/Python Files/Web/main.py", line 6, in
app = web.application(urls, globals())
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\application.py", line 62, in init
self.init_mapping(mapping)
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\application.py", line 130, in init_mapping
self.mapping = list(utils.group(mapping, 2))
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\utils.py", line 531, in group
x = list(take(seq, size))
RuntimeError: generator raised StopIteration
The webpy documentation says that the latest full release (0.39) only works on Python 2. There's work in progress towards supporting Python 3, but for now it's only available in development builds.
You can try installing one of those, with pip install web.py==0.40-dev1.
I was going into my main python folder and changing the yield thing there INSTEAD of going into the folder where my project is. The fix is changing the yield thing to the improved yield thing.
I defined a convenience function for GDB using the Python API,
import gdb
verbose = True
class HCall(gdb.Function):
def __init__(self, funcname):
super(HCall,self).__init__(funcname)
def log_call(cmd):
if verbose:
print(cmd)
try:
gdb.execute(cmd)
except Exception, e:
print (e)
import traceback
# traceback.print_stack()
traceback.format_exc()
class NewCVar(HCall):
""" allocates a c variable in heap """
def __init__(self):
super(NewCVar,self).__init__("newcvar")
def invoke(self, name, oftype):
cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
log_call(cmd)
return "$" + name
NewCVar()
I can load this file with "source usefunction.py", and print the help text with "function newcvar". Nevertheless GDB does not know about $newcvar, as I would expect (https://sourceware.org/gdb/onlinedocs/gdb/Functions-In-Python.html).
Does anyone have a clue what can I be doing wrong?
Thanks in advance!
You should probably post exactly what happens, and what you expect to happen.
I tried your program in gdb and gdb does see the function; but since there is a bug in the function, it doesn't actually work. For example I tried:
(gdb) p $newcvar("x", "int")
Traceback (most recent call last):
File "/tmp/q.py", line 23, in invoke
cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
gdb.error: Argument to arithmetic operation not a number or boolean.
Error occurred in Python convenience function: Argument to arithmetic operation not a number or boolean.
The bug is that ou're trying to gdb.execute a string that looks like call gdb.execute(...). This is weird. call evaluates an expression in the inferior, so using it with an argument containing gdb.execute is incorrect. Instead NewCVar.invoke should make a string like set variable $mumble = ....
Returning a string here is also strange.
I wonder why you want this to be a function rather than a new gdb command.
I have an IronPython script that looks for current running processes using WMI. The code looks like this:
import clr
clr.AddReference('System.Management')
from System.Management import ManagementClass
from System import Array
mc = ManagementClass('Win32_Processes')
procs = mc.GetInstances()
That last line where I call the GetInstances() method raises the following error:
Traceback (most recent call first):
File "<stdin>", line 1, in <module>
SystemError: Not Found
I am not understanding what's not being found?!? I believe that I may need to pass an instance of ManagementOperationObserver and of EnumerationOptions to GetInstance() however, I don't understand why that is, since the method with the signature Getinstance() is available in ManagementClass.
I think the only problem is that 'Win32_Processes' is a typo for 'Win32_Process'. This seems to work:
>>> mc = ManagementClass('Win32_Process')
>>> procs = mc.GetInstances()
>>> for p in procs:
... print p['Name']
...
System Idle Process
System
smss.exe
(etc)