Can i see python code

Tip: Run the Python program and then debug it directly in the command line

For your beginner, the following topic sounds a little wacky. But it helps immensely later if you want to debug a program quickly and easily.

We got to know the 2 ways we can have Python code executed:

  • Python Command Line: Type commands in the input console and execute them directly
  • Write and execute program with editor

Now a combination of both would be good - said, done and simply possible.

Execute the Python program with subsequent Python command line and access to all variables and possibilities of the executed program. And the whole thing works with a little trick.

For beginners just for the back of the head so that you can use it later or look it up.

We have a small Python program that prints "Hello World" (whatever else) and saves a variable.

We save this program with the name "hallowelt.py" and start it in the command line via "python hallowelt.py".

As output we get:

But if we now want to look up what's in the variable with the name, we are apparently out of luck. Theoretically, we can expand our program with the typical, save, execute and later delete this line again. This was only there for debugging. OR ...

Or we know the trick of getting both. The execution of the program and after the end of the program the Python command line with the typical 3 larger characters:

python -i program name.py - execution + Python command line

The trick is in the call. If we add another between and the file name, then we have this effect.

Axels-MacBook-Pro: Python-lernen.de i $ python -i hallowelt.py
Hello World
>>>

The program has now been executed. After the program has processed everything (one output of "Hello World" is not much), we land directly in the Python command line and can use it as usual.

Now we can simply query the content of the variable with the name directly. Simply type the desired command after the prompt ">>>" or, in this case, the desired variable name to get the content of the variable:

Axels-MacBook-Pro: Python-lernen.de I $ python -i hallowelt.py
Hello World
>>> message
'everything OK'
>>>

If we had integrated a function in the program, we could also use this.

We build in a function to square numbers (i.e. a number is multiplied by itself).

After restarting the program, we can now use this function in our command line:

Axels-MacBook-Pro: Python-lernen.de I $ python -i hallowelt.py
Hello World
>>> square (4)
16
>>> square (5)
25

Exit from Python command line

Simply enter our Python command line to exit.

Recommend • Social Bookmarks • Thank you