python內置函數execfile 和 內置函數exec功能實際上都同樣,不過函數execfile是python2.0版本,函數exec屬於python3.0版本,在使用的時候注意區分一下,具體使用方法參考下面的詳細介紹。python
因爲如今的python2.0版本已經中止更新,咱們主要介紹python3.0版本的內置函數exec(),其實兩個函數的參數都同樣,名字不一樣而已,語法以下:git
exec(source, globals=None, locals=None)
函數功能介紹:github
內置函數exec能夠動態的執行復雜的代碼片斷;微信
內置函數exec能夠執行py文件中的python代碼;函數
參數介紹:spa
source — py文件內容或者代碼段;code
globals — 缺省參數,默認爲空,變量做用域,全局命名空間,若是被提供,則必須是一個字典對象;對象
locals — 缺省參數,默認爲空,變量做用域,局部命名空間,若是被提供,能夠是任何映射對象;blog
返回值 — 返回值永遠是None;教程
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解憂 @Blog(我的博客地址): shuopython.com @WeChat Official Account(微信公衆號):猿說python @Github:www.github.com @File:python_exec.py @Time:2019/12/16 21:25 @Motto:不積跬步無以致千里,不積小流無以成江海,程序人生的精彩須要堅持不懈地積累! """ x = 100 source_code = """ z = 30 sum = x + y + z #一大包代碼 print(x,y,z,sum) """ def main(): y = 20 a = exec(source_code) # 100+20+30 b = exec(source_code,{'x':10,'y':20}) # 10+20+30 c = exec(source_code,{'x':10,'y':20},{'y':3,'z':4}) # 10+3+30,x是定義全局變量1,y是局部變量 print(a,b,c) # exec返回值永遠都是 None if __name__ == "__main__": main()
輸出結果:
100 20 30 150
10 20 30 60
10 3 30 43 None None None
代碼分析:source_code 是一個複雜的代碼片斷,而內置函數exec同樣能動態執行,比內置函數eval更增強悍喲!
內置函數exec除了能執行復雜的代碼片斷,還能夠執行py文件中的python代碼,舉個栗子:假若有test.txt文件,內容以下:
# e:/test.txt def main(): x = 20 y = 50 print(x+y) print("shuopython.com") if __name__ == "__main__": main()
而後使用內置函數exec執行這個txt文件的python代碼:
with open('e://test.txt','r') as f: exec(f.read())
輸出結果:
70 shuopython.com
轉載請註明:猿說Python » python execfile/exec函數