[英]I would like to check if an input is python code
我想在將輸入連接到較大的變量以最終執行之前檢查輸入是否為代碼,有什么辦法可以做到這一點? 例如:
import readline
while True:
codelines=[]
code=raw_input(">>> ")
if code.iscode():
codelines.append(code)
elif x=="end":
break
else:
print "Not usable code."
fullcode="\n".join(codelines)
try:
exec fullcode
except Exception, e:
print e
但是我不知道像.iscode()
這樣的命令
您可以嘗試使用ast.parse
解析輸入:
import ast
while True:
codelines=[]
code=raw_input(">>> ")
try:
ast.parse(code) # Try to parse the string.
except SyntaxError:
if x=="end": # If we get here, the string contains invalid code.
break
else:
print "Not usable code."
else: # Otherwise, the string was valid. So, we add it to the list.
codelines.append(code)
如果字符串不可解析(包含無效的Python代碼),則該函數將引發SyntaxError
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.