最近做的東西有個需求有點特別,在程式跑的過程中會在某一步讓使用者可以看看目前有哪些變數他可以用,然後讓他選擇要抓哪個變數出來做後續處理,概念上有點像是 gdb 的 info variables。
然而這就表示我們程式中會需要接受一個使用者輸入的字串當作 key 去存取變數,所幸程式是用 python 寫的,所以類似的方法不難做。
1. 利用 locals() 或 globals():
兩個都是 python build-in function,locals() 能列出當前所能看到的 local symbol;而 globals() 則是列出當前能存取的 global symbol。
要注意的是這邊寫的是 symbol,因為 function name 也是一種 symbol,所以不只變數,連 function 甚至 module name 都能拿到。
另一個要注意的細節就是 locals() 跟 globals() 拿到的內容不會重複,所以如果要注意要存取的 symbol 是 global scope 還是 local scope。
2.利用 exec() 或 eval() 直接執行:
這應該不難理解, exec() 或 eval() 本來就是吃一個字串後去用 python 執行得到一個結果。
範例:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_local(var_str): | |
def local_def(): | |
print(local_def) | |
local_local = 2 | |
symtbl = locals() | |
print(symtbl) | |
if var_str in symtbl: | |
print(symtbl[var_str]) | |
else: | |
print(f"Failed to find symbol '{var_str}'") | |
def print_global(var_str): | |
local_global = 3 | |
symtbl = globals() | |
print(symtbl) | |
if var_str in symtbl: | |
print(symtbl[var_str]) | |
else: | |
print(f"Failed to find symbol '{var_str}'") | |
for line in sys.stdin: | |
str = line.strip() | |
print_local(str) | |
print_global(str) |
沒有留言:
張貼留言