如何在终端中执行单行的python脚本?

mac*_*eze 3 python terminal

我将当前简单的脚本保存为Sublime Text 2 IDE中的ex1.py.

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.'
Run Code Online (Sandbox Code Playgroud)

我想在终端中从这个脚本执行一行,但是无法弄清楚如何.

该脚本执行所有七行.有没有办法指定,例如,我只想执行第3行?

dam*_*ois 10

正如@Wooble所说,这是一个奇怪的要求,但无论如何,这是一个Bash会话的解决方案:

使用awk提取你想要的行(例如第2行):

$ awk 'NR==2' ex1.py 
print "Hello Again"
Run Code Online (Sandbox Code Playgroud)

然后通过它将它提供给Python解释器stdin.

$ awk 'NR==2' ex1.py  | python
Hello Again
Run Code Online (Sandbox Code Playgroud)

您还可以指定范围

$ awk 'NR>=2 && NR<=4' ex1.py  | python
Hello Again
I like typing this.
This is fun.
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,在这种情况下,等效sed命令需要更少的击键次数

$ sed -n '2,4 p' ex1.py  | python
Hello Again
I like typing this.
This is fun.
Run Code Online (Sandbox Code Playgroud)


Mov*_*aev 5

这是Zed A. Shaw 的 Python The Hard Way课程中的一项作业,它不适合从事诸如提取文本和通过流馈送之类的奇怪事情的专业人士……无论如何,在此作业中,作者想让新手熟悉评论的工作方式在编程语言中,正如您从原始作业中看到的那样:

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.
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到作者打算如何让新手首先因难题 (2) 而感到沮丧,但在进行下一个练习 (3) 之后,让他意识到他可以使用 # 来表示他感到沮丧的问题。

所以这里是这个问题的正确答案:使用 # 注释除一行之外的所有行。