新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonexec()
這個內置函數(shù)有助于執(zhí)行動態(tài)創(chuàng)建的程序。exec()函數(shù)接收要執(zhí)行的字符串或代碼塊。它被解析并作為 python 語句執(zhí)行。

**exec(object, globals, locals)** #Where object can be a string or a code object
安全風險
如果我們使用一個 Unix 系統(tǒng)(macOS、Linux 等)并導入一個操作系統(tǒng)模塊,它有助于提供操作系統(tǒng)功能,如文件的讀、寫。并且用戶使用exec(input())輸入一個值,它可以使用命令os.system('rm -rf *')發(fā)出改變文件甚至刪除所有文件的命令。
exec()參數(shù):
取 3 個參數(shù),其中第一個參數(shù)是一個對象,如果該對象是一個字符串,它將作為 python 語句執(zhí)行,如果它是一個打開的文件,那么它將一直執(zhí)行到 EOF,如果它是一個代碼對象,那么它將被簡單地執(zhí)行。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標 | 字符串或代碼對象 | 需要 |
| 全球 | 包含全局變量的字典。 | 可選擇的 |
| 當?shù)厝?/td> | 包含局部變量的字典。 | 可選擇的 |
exec()返回值
它不返回值。它只是執(zhí)行給定的字符串或代碼對象。
Python 中exec()方法的示例
示例 1:簡單的執(zhí)行示例
x = 1
exec('print(x==1)')
exec('print(x+2)')
輸出:
True
3 示例 2:Python exec()動態(tài)代碼執(zhí)行示例
from math import *
for l in range(1, 3):
func = input("Enter Code Snippet to execute:\n")
try:
exec(func)
except Exception as ex:
print(ex)
break
print('Done')
輸出:
Enter Code Snippet to execute:
print(sqrt(16))
4.0
Enter Code Snippet to execute:
print(min(2,1))
1
Done 示例 3:將空字典作為全局參數(shù)傳遞
from math import *
exec('print(dir())', {})
# This code will raise an exception
# exec('print(sqrt(9))', {})
輸出:
['__builtins__'] 示例 4:傳遞全局和局部字典
from math import *
globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)
輸出:
['dir', 'print'] 當前名稱:創(chuàng)新互聯(lián)Python教程:Pythonexec()
鏈接URL:http://www.5511xx.com/article/djgscsj.html


咨詢
建站咨詢
