安装完Python后,Windows中:开始菜单或安装目录下就会有IDLE(开发python程序的基本IDE-集成开发环境)、帮助手册、模块文档等。Linux中:只需要在命令行中输入Python命令即可启动交互式编程。
交互式编程不需要创建脚本文件,是通过Python解释器的交互模式进来编写代码。
打开默认的交互式IDE-IDLE,提示窗口如下:
输入Python命令启动交互式编程,提示窗口如下:
[wang@rhel7-64 ~]$ python3.5
Python 3.5.1 (default, Apr 6 2016, 09:20:30)
[GCC 4.8.2 20131106 (Red Hat 4.8.2-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
在Python提示符中输入以下文本信息,然后按 Enter 键查看运行效果:
>>> print("Hello World!")
输出结果:
Hello World!
通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。当脚本执行完成后,解释器不再有效。
我们写一个简单的Python脚本程序,所有Python文件将以.py为扩展名。将以下的源代码拷贝至test.py文件中。
>>> print("Hello World!")
这里,假设你已经设置了Python解释器至PATH变量。
打开cmd命令提示符,切换至test.py所在目录(假设:E:\),使用以下命令执行脚本:
python test.py
如果不想切换目录,也可以使用绝对路径,使用以下命令执行脚本:
python E:\test.py
注意:
如果出现以下错误,请确保Python路径添加至环境变量PATH中,以及test.py所在路径正确。
‘python’ is not recognized as an internal or external command,
operable program or batch file.
python: can’t open file ‘test.py’: [Errno 2] No such file or directory
使用以下命令运行程序:
[wang@rhel7-64 ~]$ python3.5 test.py
输出结果:
Hello World!
我们尝试另一种方式来执行Python脚本。修改test.py文件,如下所示:
#!/usr/local/bin/python3.5
print("Hello World!")
这里,假定Python解释器在/usr/local/bin目录中,为test.py提添加可执行权限,使用以下命令执行脚本:
[root@rhel7-64 wang]# chmod +x test.py
[root@rhel7-64 wang]# ./test.py
输出结果:
Hello World!
注意:
如果忘记了Python的安装路径,可以通过以下命令查找:
[wang@rhel7-64 ~]$ which python3.5
/usr/local/bin/python3.5