Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run .py file until specified line number

In a linux terminal typing

python script.py 

Will run run script.py and exit the python console, but what if I just want to run a part of the script and leave the console open? For example, run script.py until line 15 and leave the console open for further scripting. How would I do this?

Let's say it's possible, then with the console still open and script.py run until line 15, can I then from inside the console call line fragments from other py files?

...something like

python script.py 15 #(opens script and runs lines 1-15 and leaves console open)

Then having the console open, I would like to run lines 25-42 from anotherscript.py

>15 lines of python code run from script.py 
> run('anotherscript.py', lines = 25-42)
> print "I'm so happy the console is still open so I can script some  more")
I'm so happy the console is still open so I can script some  more
>
like image 644
Kirbies Avatar asked Apr 27 '15 13:04

Kirbies


People also ask

How do you go to a specific line number in Python?

Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() . We can use this enumerate object with a for loop to access the line number.

Can you run Python code line by line?

One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line, which allows programming to be interactive in a way that is not directly possible with compiled languages like Fortran, C, or Java.

How do I run a .PY file in a line?

Using the python Command To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


1 Answers

Your best bet might be pdb, the Python debugger. You can start you script under pdb, set a breakpoint on line 15, and then run your script.

python -m pdb script.py
b 15                       # <-- Set breakpoint on line 15
c                          # "continue" -> run your program
# will break on line 15

You can then inspect your variables and call functions. Since Python 3.2, you can also use the interact command inside pdb to get a regular Python shell at the current execution point!

If that fits your bill and you also like IPython, you can check out IPdb, which is a bit nicer than normal pdb, and drops you into an IPython shell with interact.

like image 186
Christian Aichinger Avatar answered Oct 09 '22 10:10

Christian Aichinger