9

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
>
Kirbies
  • 777
  • 1
  • 10
  • 17
  • 1
    Why do you want to do this? – jonrsharpe Apr 27 '15 at 13:21
  • 2
    Well That's a dangerous Idea (y) – ZdaR Apr 27 '15 at 13:22
  • Define "15". Does that include lines in Python functions defined either by you or in a module? – chepner Apr 27 '15 at 13:29
  • I am imagining you have a bunch of statements in global scope ( unindented ) in script.py, and you want to stop, inspect some values and continue? you should consider defining each "step" in where you want to look at as a function, and then you can use things along the lines of "from script import step1, step2, step3" elsewhere – Caleth Apr 27 '15 at 13:44
  • @jonrsharpe : I cannot know why OP wants to do it but I often paste pieces of scripts in my IDE when doing tests or using Python IDLE as a medium level shell to interactively process data - but I must admit I would never rely on line numbers ... – Serge Ballesta Apr 27 '15 at 14:39
  • Yeah, I guess it was a bad idea. I'm new to programming without an IDE, and had some scripts on a remote server I was trying to stitch together while debugging. I should get acquainted with the python debugger. – Kirbies Apr 28 '15 at 19:41

4 Answers4

18

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.

Christian Aichinger
  • 6,989
  • 4
  • 40
  • 60
2

if you want to run script.py from line a to line b, simply use this bash snippet:

cat script.py|head -{a+b}|tail -{b-a}|python -i

replace {a+b} and {b-a} with their values

Uri Goren
  • 13,386
  • 6
  • 58
  • 110
  • Don't know either ... but your solution will close python interpreter when there's a requirement to keep it opened. – Serge Ballesta Apr 27 '15 at 14:00
  • fixed it, added the `-i` – Uri Goren Apr 27 '15 at 17:02
  • Thanks for the comment, this was what I asked for. Seems harsh with the vote down, but I guess this is to demotivate noobs like me developing bad practice. – Kirbies Apr 28 '15 at 19:43
  • Executing "from line `a` to line `b`" is bad practice indeed. It would only make sense if the file is actually a "scratchpad" and the `encoding:` line isn't in play. – ivan_pozdeev Sep 05 '16 at 14:39
1

You could use the python -i option to leave the console open at the end of the script.

It lets your script run until it exits, and you can then examine variables, call any function and any Python code, including importing and using other modules.

Of course your script needs to exit first, either at the end or, if your goal is to debug that part of the script, you could add a sys.exit() or os._exit() call where you want it to stop (such as your line 15).

For instance:

import os
print "Script starting"
a=1
def f(x):
    return x

print "Exiting on line 8"
os._exit(0) # to avoid the standard SystemExit exception 

print "Code continuing"

Usage example:

python -i test_exit.py
Scrit starting
Exiting on line 8
>>> print a
1
>>> f(4)
4
>>>
GCord
  • 146
  • 6
  • _"if your goal is to debug that part of the script..."_ - with `.exit`, they won't be able to execute the script further other than by copy-pasting, so the advice doesn't further the goal it claims to. The `python -i` part _is_ useful if the file is some initialization for the interactive session instead. (the 1st part thus warrants an upvote and the 2nd - downvote, so I do neither) – ivan_pozdeev Sep 05 '16 at 14:42
0

You cannot do that directly but you can do something similar from inside Python console (or IDLE) with exec :

  • just open you favorite Python console
  • load wanted lines into a string and exec them :

    script = 'script.py'
    txt = ''
    with open(script) as sc:
        for i, line in enumerate(sc):
            if i >= begline and i<= endline:
            txt = txt + line
    exec(txt)
    

You can even write your own partial script runner based on that code ...

EDIT

I must admit that above answer alone really deserved to be downvoted. It is technically correct and probably the one that most closely meet what you asked for. But I should have warned you that it is bad pratice. Relying on line numbers to load pieces of source files is error prone and you should avoid it unless you really know what you are doing and why you do it that way. Python debugger at least allows you to control what are the lines you are about to execute.

If you really have to use this solution be sure to always print and double check the lines that you are about to execute. IMHO it is always both simpler and safer to copy and past lines in an IDE like IDLE that is packaged into any standard Python installation.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Looks like this is not seen as a good idea by the community :-( ... I honestly thought it was not so far from what OP asked for, as he even asked the possibility to read (from `anotherscript.py`) lines in the middle of file (starting at 25) what is allowed with this solution and not with upvoted one. Can someone tell me what is wrong ? – Serge Ballesta Apr 27 '15 at 13:53
  • A discussion on meta let me think that even if that solution is technically correct, it is dangerous. *Caveat emptor* ! – Serge Ballesta Apr 27 '15 at 21:27