目錄
前言
python內置函數execfile 和 內置函數exec功能實際上都一樣,不過函數execfile是python2.0版本,函數exec屬於python3.0版本,在使用的時候注意區分一下,具體使用方法參考下面的詳細介紹。
一.execfile/exec函數簡介
由於現在的python2.0版本已經停止更新,我們主要介紹python3.0版本的內置函數exec(),其實兩個函數的參數都一樣,名字不同而已,語法如下:
exec(source, globals=None, locals=None)
函數功能介紹:
內置函數exec可以動態的執行復雜的代碼片段;
內置函數exec可以執行py文件中的python代碼;
參數介紹:
source — py文件內容或者代碼段;
globals — 缺省參數,默認爲空,變量作用域,全局命名空間,如果被提供,則必須是一個字典對象;
locals — 缺省參數,默認爲空,變量作用域,局部命名空間,如果被提供,可以是任何映射對象;
返回值 — 返回值永遠是None;
二.execfile/exec函數使用
1.exec函數執行代碼段
# !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更加強悍喲!
2.exec函數執行py文件
內置函數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函數
技術交流、商務合作請直接聯繫博主
掃碼或搜索: 猿說python
猿說python
微信公衆號 掃一掃關注