按照官方的解释,加-m选项是以模块的方式执行,那么到底是什么意思呢?
首先我们来看下这段简单的测试代码:
#!/usr/bin/python
import sys
print sys.path
我们把这个文件放在/home/hank/下面,然后在根目录下分别执行:
hank@ubuntu:/$ pwd
/
hank@ubuntu:/$ python /home/hank/test.py
['/home/hank', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
hank@ubuntu:/$ python -m /home/hank/test.py
/usr/bin/python: Import by filename is not supported.
hank@ubuntu:/$ python -m /home/hank/test
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
注意,当我们使用-m选项的时候,一般使用模块名即可,系统自动在后面补齐*.py的后缀。另外,注意sys.path的输出,在加了“-m”选项之后,sys.path包含了当前目录。那么这会带来什么样的效果呢,且看下面的代码:
package1/__init__.py
mod1.py
package2/__init__.py
run.py
run.py的代码如下:
#!/usr/bin/python
import sys
from package1 import mod1
print sys.path
分别带“-m”执行和不带“-m”执行run.py脚本,结果如下:
hank@ubuntu:~$ python -m package2/run['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
hank@ubuntu:~$ python package2/run.py Traceback (most recent call last): File "package2/run.py", line 3, infrom package1 import mod1
ImportError: No module named package1
可以看到不带“-m”选项执行时,由于sys.path不包含当前目录,所以当执行from package1 import mod1会搜不到package1这个包。
网友评论