Python标准库系列之模块默认全局变量

简介:

当我们创建了一个自己写的模块后,那么这个模块本身就自带了好几个全局变量,这些全局变量在每个文件中都存在。

查看当前py文件的全局变量

1
2
3
[root@ansheng ~] # echo 'print(vars())' > scripts.py      
[root@ansheng ~] # python scripts.py 
{ '__builtins__' : <module  '__builtin__'  (built- in )>,  '__name__' '__main__' '__file__' 'scripts.py' '__doc__' : None,  '__package__' : None}

默认全局变量

变量名 说明
__doc__ py文件的注释,是对文件的注释
__file__ 获取当前文件路径
__package__ 返回导入的文件所在包,用.分隔,如果是当前文件则返回None
__cached__ 返回导入的其他文件pyc文件路径,当前文件返回None
_name_ 如果是主文件则返回__main__ 否则等于模块名

没有列出来的就是没必要许了解的

实例

返回scripts文件的注释及文件路径

1
2
3
4
5
6
7
[root@ansheng ~] # cat scripts.py 
#!/usr/bin/env pyton# 文件的注释顶格写
"" "  Python file comments " ""
# 输出文件注释
print( "comments" ,__doc__)
# 输出文件路径
print( "file path" ,__file__)

执行脚本

1
2
3
4
[root@ansheng ~] # python scripts.py 
( 'comments' '  Python file comments ' )
 
( 'file path' 'scripts.py' )

__name__函数的应用

查看当前目录下面的文件及文件内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@ansheng ~] # ls -l
total 8
drwxr-xr-x 2 root root 4096 May 24 21:36 lib
-rw-r--r-- 1 root root   80 May 24 21:37 scripts.py
[root@ansheng ~] # ls -l lib/
total 12
-rwxr-xr-x 1 root root  54 May 24 21:36 f1.py
-rw-r--r-- 1 root root   0 May 24 21:34 __init__.py
[root@ansheng ~] # cat lib/f1.py
#!/usr/bin/env python
def  echo ():
  print( "lib/f1.py" )
[root@ansheng ~] # cat scripts.py 
#!/usr/bin/env pyton
from lib  import  f1
 
if  __name__ ==  "__main__" :
   f1. echo ()
执行`scripts.py`脚本,脚本会调用`lib/f1.py`文件,而`lib/f1.py`文件会输出`lib/f1.py`,所以执行`scripts.py`文件的时候自然也会输出`lib/f1.py`

```bash
[root@ansheng ~]# python scripts.py 
# 正如我们看到的,会输出下面的内容
lib/f1.py

这是我们再创建一个scripts1.py文件

1
[root@ansheng ~] # touch scripts1.py

scripts1.py文件内容如下

1
2
[root@ansheng ~] # cat scripts1.py 
#!/usr/bin/env pytonimport scripts

文件创建好后执行他,我们会发现什么也没有输出

[root@ansheng ~]# python scripts1.py

然后我们把scripts.py脚本文件内容改为如下

[root@ansheng ~]# cat scripts.py#!/usr/bin/env pytonfrom lib import f1
f1.echo()

再次执行scripts1.py脚本这是就会输出lib/f1.py

[root@ansheng ~]# python scripts1.py 
lib/f1.py

为什么会出现上面的情况呢?

因为原来的scripts.py文件加了if判断,其意思就是说如果__name__的值等于"__main__",那么我就执行f1.echo()方法,否则就什么也不做,当scripts.py文件被我们直接执行的时候的__name__返回结果是"__main__",如果被别的文件调用了,那么__name__返回的结果是"scripts"

自动把当前目录下面的bin目录添加到python的PATH变量中

目录结构及脚本内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[root@ansheng ~] # tree /tmp/
/tmp/
├── bin
│   ├── f1.py
│   └── __init__.py
└── scripts.py
 
1 directory, 3 files
[root@ansheng ~] # cat /tmp/scripts.py 
#!/usr/bin/env pyton
import  os
import  sys
 
path = os.path. dirname (__file__)
mod_path = os.path. join (path, "bin" )
 
sys.path.append(mod_path)
for  in  sys.path:
     print(n)

执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@ansheng ~] # python /tmp/scripts.py 
/tmp
/usr/lib64/python26 .zip
/usr/lib64/python2 .6
/usr/lib64/python2 .6 /plat-linux2
/usr/lib64/python2 .6 /lib-tk
/usr/lib64/python2 .6 /lib-old
/usr/lib64/python2 .6 /lib-dynload
/usr/lib64/python2 .6 /site-packages
/usr/lib64/python2 .6 /site-packages/gtk-2 .0
/usr/lib/python2 .6 /site-packages
/usr/lib/python2 .6 /site-packages/setuptools-0 .6c11-py2.6.egg-info
/tmp/bin

This site is open source. Improve this page.











本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/2089744,如需转载请自行联系原作者
目录
相关文章
Python
13 0
|
1天前
|
JSON 数据格式 索引
python 又一个点运算符操作的字典库:Munch
python 又一个点运算符操作的字典库:Munch
10 0
|
1天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
11 0
|
1天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,提供DataFrame数据结构。基本步骤包括导入库、创建DataFrame及进行数据筛选。示例代码展示了如何通过布尔索引、`query()`和`loc[]`方法筛选`Age`大于19的记录。
10 0
|
2天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`。`rank()`函数用于计算排名,如`df[&#39;A&#39;].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`和分别对&#39;A&#39;、&#39;B&#39;列排名。
13 2
|
3天前
|
算法 Python
请解释Python中的关联规则挖掘以及如何使用Sklearn库实现它。
使用Python的mlxtend库,可以通过Apriori算法进行关联规则挖掘。首先导入TransactionEncoder和apriori等模块,然后准备数据集(如购买行为列表)。对数据集编码并转换后,应用Apriori算法找到频繁项集(设置最小支持度)。最后,生成关联规则并计算置信度(设定最小置信度阈值)。通过调整这些参数可以优化结果。
25 9
|
3天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行或列;3) `fillna()`用常数、前后值填充;4) `interpolate()`进行插值填充。根据需求选择合适的方法处理数据缺失。
35 9
|
3天前
|
索引 Python
如何在Python中使用Pandas库进行季节性调整?
在Python中使用Pandas和Statsmodels进行季节性调整的步骤包括:导入pandas和seasonal_decompose模块,准备时间序列DataFrame,调用`seasonal_decompose()`函数分解数据为趋势、季节性和残差,可选地绘制图表分析,以及根据需求去除季节性影响(如将原始数据减去季节性成分)。这是对时间序列数据进行季节性分析的基础流程。
19 2
|
4天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
5天前
|
缓存 自然语言处理 数据处理
Python自然语言处理面试:NLTK、SpaCy与Hugging Face库详解
【4月更文挑战第16天】本文介绍了Python NLP面试中NLTK、SpaCy和Hugging Face库的常见问题和易错点。通过示例代码展示了如何进行分词、词性标注、命名实体识别、相似度计算、依存关系分析、文本分类及预训练模型调用等任务。重点强调了理解库功能、预处理、模型选择、性能优化和模型解释性的重要性,帮助面试者提升NLP技术展示。
22 5

热门文章

最新文章