打开terminal , 直接输入 python
wenqidongdeMBP:~ wenqidong$ python
Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
首页看到Python版本是2.7.10,最后出现三个>>>
,直接在这后面输入python代码就能执行,例如:
wenqidongdeMBP:~ wenqidong$ python
Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
SyntaxError: EOL while scanning string literal
>>> print hello world;
File "<stdin>", line 1
print hello world;
^
SyntaxError: invalid syntax
>>> print "hello world"
hello world
>>>
字符串需要引号,第一个没引号,提示出错,第二个成功输出hello world;
wenqidongdeMBP:Versions wenqidong$ pwd
/System/Library/Frameworks/Python.framework/Versions
wenqidongdeMBP:Versions wenqidong$ ls
2.3 2.5 2.6 2.7 Current
wenqidongdeMBP:Versions wenqidong$ python -V
Python 2.7.10
wenqidongdeMBP:Versions wenqidong$
用Homebrew搜一下python3
brew search python3
结果如下:
wenqidongdeMBP:Versions wenqidong$ brew search python3
==> Formulae
boost-python3 python3 ✔ python@3 ✔
If you meant "python3" specifically:
It was migrated from homebrew/cask to homebrew/core.
直接安装
brew install python3
提示已经存在了,可能是之前安装过,就不重复安装了...
wenqidongdeMBP:Versions wenqidong$ brew install python3
Error: python 3.7.2_1 is already installed
To upgrade to 3.7.2_2, run `brew upgrade python`
wenqidongdeMBP:Versions wenqidong$ python3 -V
Python 3.7.2
wenqidongdeMBP:Versions wenqidong$
查看安装信息
wenqidongdeMBP:Versions wenqidong$ brew info python3
python: stable 3.7.2 (bottled), HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/usr/local/Cellar/python/3.7.2_1 (3,242 files, 51.6MB) *
Poured from bottle on 2019-01-17 at 14:14:21
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/python.rb
==> Dependencies
Build: pkg-config ✔
Required: gdbm ✔, openssl ✔, readline ✔, sqlite ✘, xz ✔
==> Options
--HEAD
Install HEAD version
==> Caveats
Python has been installed as
/usr/local/bin/python3
...
以下为Python命令行参数:
选项 | 描述 |
---|---|
-d | 在解析时显示调试信息 |
-O | 生成优化代码 ( .pyo 文件 ) |
-S | 启动时不引入查找Python路径的位置 |
-V | 输出Python版本号 |
-X | 从 1.6版本之后基于内建的异常(仅仅用于字符串)已过时。 |
-c cmd | 执行 Python 脚本,并将运行结果作为 cmd 字符串。 |
file | 在给定的python文件执行python脚本。 |
#!/usr/bin/python3
print("Hello, World!")
Python3中 print()是一个内置函数,Python2中使用 print "Hello, World!";
关于脚本第一行的 #!/usr/bin/python
的解释,相信很多不熟悉 Linux 系统的同学需要普及这个知识,脚本语言的第一行,只对 Linux/Unix 用户适用,用来指定本脚本用什么解释器来执行。
有这句的,加上执行权限后,可以直接用 ./ 执行,不然会出错,因为找不到 python 解释器。
#!/usr/bin/python 是告诉操作系统执行这个脚本的时候,调用 /usr/bin 下的 python 解释器。
#!/usr/bin/env python 这种用法是为了防止操作系统用户没有将 python 装在默认的 /usr/bin 路径里。当系统看到这一行的时候,首先会到 env 设置里查找 python 的安装路径,再调用对应路径下的解释器程序完成操作。
#!/usr/bin/python 相当于写死了 python 路径。
#!/usr/bin/env python 会去环境设置寻找 python 目录,可以增强代码的可移植性,推荐这种写法。