GDB Python API: How to access events in Python - python

I am trying to write a Python script for GDB that uses the events gdb.events.inferior_call_pre and events.inferior_call_post. However, those events are not defined in gdb.events:
>(gdb) python print(dir(gdb.events))
['__doc__', '__name__', '__package__', 'cont', 'exited', 'new_objfile', 'stop']
The above was done without a program loaded. I have also loaded a C program, run it until a breakpoint, and then executed the command with the same result.
I am running CentOS 7 with gdb 7.6.1.
I downloaded and compiled the source (with --with-python=yes) for gdb 7.12 with less success:
(gdb) python print(dir(gdb.events))
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'gdb' is not defined
Error while executing Python code.
Any help is greatly appreciated.

According to gdb's NEWS file, support for the events gdb.events.inferior_call_pre and gdb.events.inferior_call_post was added in gdb 7.9.
If you're compiling gdb from source, the gdb python module can be found in the directory gdb-7.12.1/gdb/python/lib/gdb, which gets copied to gdb-7.12.1/gdb/data-directory/python/gdb.
When you do make install, it gets copied to <prefix directory>/share/gdb/python/gdb.
If the latter directory can't be found at runtime - for instance, if you run gdb from the source directory without having done make install - gdb ought to complain at startup:
$ ./gdb
Python Exception <type 'exceptions.ImportError'> No module named gdb:
./gdb: warning:
Could not load the Python gdb module from `<prefix directory>/share/gdb/python'.
Limited Python support is available from the _gdb module.
Suggest passing --data-directory=/path/to/gdb/data-directory.
The data directory also contains files with lists of available system calls for various target architectures. It's worth making sure that gdb has access to it.
If you can't run make install but have to run gdb directly from the source directory, cd to gdb-7.12.1/gdb and run ./gdb --data-directory=./data-directory .

Related

Running an Nsight Systems report python script independently

I've tweaked a copy of one of the Nsight Systems report scripts (gpukernsum), and I now want to run it myself. So, I write:
./gpukernsum.py report.sqlite
This doesn't work; I get:
ERROR: Script 'gpukernsum.py' encountered an internal error.
$ ./gpukernsum.py report.sqlite
File "./gpukernsum.py", line 40
"""
^
SyntaxError: invalid syntax
I know this is because f"""whatever""" is Python-3 syntax, so I change the script's hash-bang line from:
#!/usr/bin/env python
to:
#!/usr/bin/env python3
and now I get:
$ ./gpukernsum.py report.sqlite
Traceback (most recent call last):
File "/path/to/./gpukernsum.py", line 7, in <module>
import nsysstats
ModuleNotFoundError: No module named 'nsysstats'
So I added the relevant directory to the lookup path:
export PYTHONPATH="$PYTHONPATH:/opt/nvidia/nsight-systems/2022.1.1/host-linux-x64/python/lib"
and now I get:
$ ./gpukernsum.py report.sqlite
near "WITH": syntax error
... and I'm stuck. The relevant area of the code is:
and not a percentage of the application wall or CPU execution time.
"""
query_stub = """
WITH
summary AS (
SELECT
coalesce({NAME_COL_NAME}, demangledName) AS nameId,
i.e. the "WITH" is part of a string literal which is an SQL query. So, what's the problem? Is Python complaining? Is sqlite complaining?
Note:
Nsight Systems 2022.1.1
CentOS 7
I'm using the original gpukernsum.py code - I have not made any changes to it (other than as described above).
My system has Python 3.9.1 for python3.
A workaround answer:
Nsight Systems bundles its own version of Python, with lib and bin directories.
If you run your script with this specific version, having set PYTHONPATH as described in your question - then the script will work. It's what Nsight itself does, after all.

Python fails to find module when invoked as script ; finds it interactively

I'm trying to run a python script containing submodules from Github to finetune its model.
The final step of the process is to invoke
python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume
However, doing from root of repo (and from realesrgan folder for that matter) so results in:
Traceback (most recent call last):
File "D:\Real-ESRGAN\realesrgan\train.py", line 5, in
import realesrgan.archs
ModuleNotFoundError: No module named 'realesrgan'
Yet, by launching python interactively from repo root (just "python") and then invoking
import realesrgan.archs
results in me being able to import it without any problem. All mentioned folders have required init.py in them.
This is my first time seeing discrepancy between calling a script and interactive python and I'm wondering, what can cause this.
System specifics just in case:
Windows 11
Python 3.9.9
python script execution fails from either powershell/cmd/file explorer

Suggestion to do close source my python project

I am new in python and pyqt5. I wrote a simple project by python and pyqt5 and now i want to close source code to not seen my source code. I think by obfuscate i can do this so i have installed pyminifier.
sudo apt install python-setuptools
pip3 install pyminifier
In my project i have a few class. By this command i can obfuscate one class of my project:
pyminifier --obfuscate --gzip MainWindow.py
import zlib, base64
exec(zlib.decompress(base64.b64decode('eJytVU1v2zAMvftXaLnUGQJtl10G+NAmHbAObfPRIAWGwVBtylZrS64k56PYj59oO46dpNtlh8QW+UQ9PlI01yonS3HLhF.....
The above output is shown in my terminal after running pyminifier --obfuscate.
Does it commend must be run for each class and copy output code to other new file?
If i do, I think these class's that imported together properly do not known each other and finally application do not be run!!! I am right?
Edit
I obfuscate entrypoint of my project by this command:
pyminifier --obfuscate --gzip Main.py
import zlib, base64
exec(zlib.decompress(base64.b64decode('eJzLzC3ILypRKK4s5sqyBZJ6qRWZJVzuYGZiUXoZV1pRfq5CQGVgialeYEl4Zkp6akmxQiZEV6BjQUFOZnJiSWZ+HkShb2JmXnhmXkp+OUwNQgSomMvHFlmPhrsmV6UtigoNTa4sDR+gK1KTNTQ1uQAalDgb')))
# Created by pyminifier (https://github.com/liftoff/pyminifier)
and i copied this codes into other file.py and i run app but i got Error:
python new.py
Traceback (most recent call last):
File "new.py", line 2, in <module>
exec(zlib.decompress(base64.b64decode('eJzLzC3ILypRKK4s5sqyBZJ6qRWZJVzuYGZiUXoZV1pRfq5CQGVgialeYEl4Zkp6akmxQiZEV6BjQUFOZnJiSWZ+HkShb2JmXnhmXkp+OUwNQgSomMvHFlmPhrsmV6UtigoNTa4sDR+gK1KTNTQ1uQAalDgb')))
File "<string>", line 8
j(L.exec())
^
SyntaxError: invalid syntax
Are you running a Python 3 program with Python 2? The error message only makes sense if you are using Python 2, where exec was a keyword.
For obfuscating multiple files, see http://liftoff.github.io/pyminifier/pyminifier.html:
Pyminifier can now minify/obfuscate an arbitrary number of Python scripts in one go. For example, ./pyminifier.py -O *.py will minify and obfuscate all files in the current directory ending in .py. To prevent issues with using differentiated obfuscated identifiers across multiple files, pyminifier will keep track of what replaces what via a lookup table to ensure foo_module.whatever is gets the same replacement across all source files. Added in version 2.0

How to run this .py script correctly?

I downloaded a program called "A ren'py script decompiler," and I cannot for the life of me work out how to run it.
I googled a bit to discover that the files I had downloaded, which were in ".py" format, referred to Python, (yes, this is the level I am on,) so I downloaded it, and after a bit more googling, managed to run the script.
However I have still no idea how to get this thing to actually do what I want, as when I try to copy the commands from the README, it just brings up errors, and half the time I don't even understand what the README is saying in the first place. For example: "You can either use the -b argument to specify the directory in which renpy lies or place the renpy module in your Python module search path." This is gibberish to me.
So I know this is a big ask, but apparently getting this to run is supposed to be pretty simple -- it's just a lightweight program/script/thing that decompiles .rpyc scripts. So does anyone know how I can get it to work?
This is the thing: https://github.com/yuriks/unrpyc
When I run the script in Python it just says:
usage: unrpyc.py [-h] [-c] [-b BASEDIR] [-d]
[--python-screens | --ast-screens | --no-screens | --single-line-screen-kwargs]
file [file ...]
unrpyc.py: error: too few arguments
And then after that I don't know what to type to get it to work anyways.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
--basedir
NameError: name 'basedir' is not defined
I'm the maintainer of unpryc
The script should be ran with python 2.7. Also I'm glad to tell you that in the more recent version of the decompiler (http://github.com/CensoredUsername/unrpyc) the dependency on renpy has been removed, so you no longer have to fiddle with the --basedir option.
regarding the error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
--basedir
NameError: name 'basedir' is not defined
I'd guess that's caused because you're trying to run the command in a python shell instead of a normal command prompt. If you want to call the script normally open a command prompt (I think you're on windows, so it'd be cmd.exe) and run the command:
path_to_python_executable unrpyc.py script_you_want_to_decompile.rpyc
path_to_python_executable is usually C:\Python27\python.exe
That should work.
You won't need most options; the only one you probably need is the -b switch, and of course the script you want to decompile.
The -b (or --basedir) option tells this script where to find the Ren'Py source code; you need to have that program installed too, and then give the directory where it's Python modules are located to this script. Presumably just downloading the SDK, extracting that somewhere and naming that path with teh -b switch is enough:
unrpyc.py -b /path/to/renpy/modules/directory script_you_want_to_decompile.rpy

python gtk module opens display on import

I'm using the trick "python -c 'import myscript.py'" to perform a syntax check on a script which uses 'import gtk'.
I get the following error when performing the syntax check, which implies that the gtk module is executing a check for the X display, even though all that's being done at this point is to import the module.
Traceback (most recent call last):
File "<stdin>", line 15, in ?
File "myscript.py", line 21, in ?
import gtk
File "/usr/src/build/463937-i386/install/usr/lib/python2.3/site-packages/gtk-2.0/gtk/__init__.py", line 37, in ?
RuntimeError: could not open display
Is there a way to avoid this error when performing the syntax check?
Before you ask - I'm not able to set $DISPLAY before the syntax check is run. The check is being run on remote servers as part of a distributed build system. These servers do not have an X display available.
Importing modules in Python executes their code!
Well-behaved modules use the if __name__ == '__main__' trick to avoid side effects, but they can still fail - as happened to you.
[BTW, getting to ImportError means the whole file already has correct syntax.]
If you just want to check syntax, without running at all:
python -m py_compile my_script.py
will check one file (and produce a .pyc as a side effect).
python -m compileall ./
will check a whole dir recursively.
python -c 'compile(open("myscript.py").read(), "myscript.py", "exec")'
avoids creating a .pyc.
But note that merely checking the syntax in Python catches very few bugs! Importing does catch more, e.g. mispelled names. For even better checks, use tools like Pychecker / Pyflakes.
What exactly do you mean by 'syntax checking'?
Can't you use a tool like pylint to check for syntax errors?
Otherwise: a very ugly (but probably possible hack):
In your python script detect whether X is present.
If it's not => use GTK on DirectFramebuffer (no X needed then). You'll need to compile GTK on DirectFB (and/or pygtk) from source (some pointers here).
If the remote machine has vncserver installed, you can have a dummy server running and connect to that. Sample instructions:
remotemachine $ vncserver -depth 16 -geometry 800x600 :7
New 'X' desktop is remotemachine:7
Starting applications specified in /home/user/.vnc/xstartup
Log file is /home/user/.vnc/userve:7.log
remotemachine $ DISPLAY=:7 python -c 'import myscript.py'
…
remotemachine $ vncserver -kill :7
Killing Xtightvnc process ID 32058
In your myscript.py, you could do like this
if __name__=="__main__":
import gtk
That will not execute gtk's __init__.py when you do "python -c 'import myscript.py'"
If you are editing with IDLE, Alt+X will check syntax of current file without running it.

Categories