-1

I have the file main.py containing the code

def my_function():

    a = 0
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()

I execute this script from a terminal / shell.

If I run the script with python -i main.py all the variables are already gone because the function my_function has ran out of scope.

How do I interrupt the running of the script after the command a = 0 and set a to the value 1?

EDIT My goal with this question is to learn how I can apply some commands on variables that are the result of a function, even after the function has finished. So the code I wrote above is just a (minimum working) example.

Adriaan
  • 715
  • 10
  • 22

1 Answers1

1

You can use Python debuger's set_trace() to break into the debugger from a running program and manipulate variables. Use debugger command c(ont(inue)) to continue execution.

def my_function():

    a = 0
    import pdb
    pdb.set_trace()
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13
  • Didn't know the `set_trace()` command yet. Very useful. Though I'm not sure how to manipulate the variables I must say. I'm not sure how to use the `run` and `p` command as explained at https://docs.python.org/3/library/pdb.html#pdbcommand-continue – Adriaan May 27 '19 at 12:02
  • When you break into debugger you can write Python code like `a=4`, `print(a)` or whatever you want and then just use the continue command to continue execution. – Toni Sredanović May 27 '19 at 12:06
  • Your suggestion does not seem to work. No matter how I try to manipulate `a`, it's value remains equal to 0 if I run `print(a)`. – Adriaan May 27 '19 at 12:12
  • This did not occur to me straight away but variable named `a` conflicts with PDB commands so to change it you must use an exclamation mark ! before a statement (`!a = 4`). More about it [here](https://stackoverflow.com/questions/21123473/how-do-i-manipulate-a-variable-whose-name-conflicts-with-pdb-commands). – Toni Sredanović May 27 '19 at 12:25