在linux 下建立一个文件叫hello.py,并输入python
1
|
print
(
"Hello World!"
)
|
而后执行命令:python hello.py ,输出linux
1
2
3
|
localhost:~ jieli$ vim hello.py
localhost:~ jieli$ python hello.py
Hello World!
|
指定解释器shell
上一步中执行 python hello.py 时,明确的指出 hello.py 脚本由 python 解释器来执行。vim
若是想要相似于执行shell脚本同样执行python脚本,例: ./hello.py
,那么就须要在 hello.py 文件的头部指定解释器,以下:bash
1
2
3
|
#!/usr/bin/env python
print
"hello,world"
|
如此一来,执行: ./hello.py
便可。ide
ps:执行前需给予 hello.py 执行权限,chmod 755 hello.pyspa
在交互器中执行 命令行
除了把程序写在文件里,还能够直接调用python自带的交互器运行代码, code
1
2
3
4
5
6
|
localhost:~ jieli$ python
Python
2.7
.
10
(default,
Oct
23
2015
,
18
:
05
:
06
)
[GCC
4.2
.
1
Compatible Apple LLVM
7.0
.
0
(clang
-
700.0
.
59.5
)] on darwin
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
>>>
print
(
"Hello World!"
)
Hello World!
|
请注意区分命令行模式和Python交互模式。orm
看到相似C:\>
是在Windows提供的命令行模式:
在命令行模式下,能够执行python
进入Python交互式环境,也能够执行python hello.py
运行一个.py
文件。
看到>>>
是在Python交互式环境下:
在Python交互式环境下,只能输入Python代码并马上执行。
此外,在命令行模式运行.py
文件和在Python交互式环境下直接运行Python代码有所不一样。Python交互式环境会把每一行Python代码的结果自动打印出来,可是,直接运行Python代码却不会。
例如,在Python交互式环境下,输入:
>>> 100 + 200 + 300600
直接能够看到结果600
。
可是,写一个calc.py
的文件,内容以下:
100 + 200 + 300
而后在命令行模式下执行:
C:\work>python calc.py
发现什么输出都没有。
这是正常的。想要输出结果,必须本身用print()
打印出来。把calc.py
改造一下:
print(100 + 200 + 300)
再执行,就能够看到结果:
C:\work>python calc.py 600
在Python交互式命令行下,能够直接输入代码,而后执行,并马上获得结果。