简体   繁体   中英

How to check if string is valid python code (runtime error)

Is there a possibility to check on Runtime errors? It is clear from a string that pri1nt is a function and it is not defined in this string.

import ast

def is_valid_python(code):
  try:
     ast.parse(code)
  except SyntaxError:
     return False
  return True

mycode = 'pri1nt("hello world")'

is_valid_python(mycode) # true

exec(mycode) # NameError: name 'pri1nt' is not defined

Try using BaseException instead of SyntaxError . This would check every type of python error, including NameError . Also, because ast.parse never raises any errors, you should use exec instead.

So it should be like this:

def is_valid_python(code):
  try:
     exec(code)
  except BaseException:
     return False
  Return True

mycode = 'pri1nt("hello world")'

is_valid_python(mycode) # false

maybe something like this?

import subprocess

script_string = "prnt(\"Hello World!\")"    
proc = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
res = proc.communicate(bytes(script_string, "UTF-8"))

what it basically does is pipeing the string to a python interpreter. if no error, then the script_string is valid.

Edit: res will contain (stdout_data, stderr_data) (see https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM