Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a single line of a python script in Terminal?

I have the current simple script saved as ex1.py in the Sublime Text 2 IDE.

print "Hello world!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'

I would like to execute a single line from this script in Terminal, but haven't been able to figure out how.

The script executes all seven lines. Is there a way to specify, for example, that I just want to execute line 3?

like image 984
macnsteeeze Avatar asked Jun 27 '14 13:06

macnsteeeze


3 Answers

As @Wooble says, this is an odd requirement, but anyway, here is a solution in a Bash session:

Use awk to extract the line you want (e.g. line 2):

$ awk 'NR==2' ex1.py 
print "Hello Again"

Then feed it to the Python interpreter through stdin.

$ awk 'NR==2' ex1.py  | python
Hello Again

You can also specify a range

$ awk 'NR>=2 && NR<=4' ex1.py  | python
Hello Again
I like typing this.
This is fun.

Edit: note that in this case, the equivalent sed command requires fewer keystrokes

$ sed -n '2,4 p' ex1.py  | python
Hello Again
I like typing this.
This is fun.
like image 110
damienfrancois Avatar answered Nov 14 '22 22:11

damienfrancois


It's an assignment from course Python The Hard Way by Zed A. Shaw and it's not for professionals with doing weird things like extracting text and feeding it through streams... Anyway, in this assignment author wanted to make newbies acquainted with the way commentaries work in programming languages, as you can see from the original assignment:

The Study Drills contain things you should try to do. If you can't, skip it and come back later.
For this exercise, try these things:

1. Make your script print another line.
2. Make your script print only one of the lines.
3. Put a # (octothorpe) character at the beginning of a line. What did it do? Try to find out what this character does.

Here you can see how author intends to make newbie first frustrated by the hard question (2), but after going to the next exercise (3) make him realize that he can use # for the one which he got frustrated about.

So here's the right answer specifically to this question: use # to comment all lines but one.

like image 33
Movsar Bekaev Avatar answered Nov 14 '22 23:11

Movsar Bekaev


You could use (pdb):

import pdb;pdb.set_trace()
print "Hello world!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'

You could then step through:

step

or jump to a single line (line 3):

j 3

Or if you want to run a single command from terminal: python -c "print('hello there')"

like image 29
jmunsch Avatar answered Nov 14 '22 23:11

jmunsch