简体   繁体   中英

How to pass arguments to a python gdb script launched from command line

I'd like to pass some command line arguments to a python script run via gdb command, but importing the gdb module in python removes the argv attribute from sys. How do I access arg1 and arg2 within my python script shown in my example?

Command line execution:

$ gdb -x a.py --args python -arg1 -arg2

a.py:

#!/usr/bin/env python
import gdb
import sys
print('The args are: {0}'.format(sys.argv))
gdb.execute('quit')

Error raised:

AttributeError: 'module' object has no attribute 'argv'

Versions:

  • GNU gdb (GDB) 7.2
  • Python 2.6.6

Edit:

The end target I'll be debugging is a C executable that is already running, so I'll be attaching to it later in the script, so gdb -x a.py --args python -arg1 -arg2 is not correct either since the python part prints a gdb error: Reading symbols from /usr/bin/python...(no debugging symbols found)...done. ...

-ex py

This is a possibility:

argv.py

print(arg0)
print(arg1)

Invocation:

gdb --batch -ex 'py arg0 = 12;arg1 = 3.4' -x argv.py

or equivalently:

gdb --batch -ex 'py arg0 = 12' -ex 'py arg1 = 3.4' -x argv.py

Output:

12
3.4

Then you could wrap that in the following script:

#!/usr/bin/env bash

doc="
Pass parameters to python script.

Usage:

  $0 scrpit.py 1 2

Where scrpit.py uses the arguments like:

  print(arg0)
  print(arg1)
"

py="$1"
shift
cli=''
i=0
for arg in $*; do
  cli="$cli -ex 'py arg$i = $arg'"
  i=$(($i+1))
done
eval gdb --batch $cli -x "$py"

Tested on Python 3.8.6, GDB 9.2, Ubuntu 20.10.

It's not totally clear to me what you are trying to do.

An invocation of the form:

gdb --args something arg arg

Tells gdb to use something as the program to be debugged, with arg arg as the initial command-line arguments for the run command. You can inspect these inside gdb with show args .

So, your command is saying "I want to debug the python executable, passing it some arguments".

However, later you say you plan to attach to some already-running executable.

So, I think you're probably trying to script gdb in Python -- not debug the python executable.

The good news is, this is possible, just not the way you've written it. Instead you have a couple choices:

  • Make a .py file holding your script and tell gdb to source it, eg, with gdb -x myscript.py (which you've already done...)

  • Use -ex to invoke some Python explicitly, like -ex 'python print 23' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM