5Ermacs 5Ermacs - 3 years ago 198
Linux Question

Compiling a string using python(not running) on linux command line

I'm trying to do something for a project that I cannot find the answer to after searching and trying some different code.

What I'm trying to do is receive a string from a client(sent through via post, and I have to use this method, teacher's orders), and then compile this string using exec() in php file. Basically I'm "grading" a python code snippet sent to me as a string. I'm also doing this on the Andrew file system server(afs).

I'm not very experienced with python, mostly used other languages, but I'm able to make a python executable with php exec and also just compile it using cython(it's what the linux machines on our school have, not sure if I should use this). I got this to work with files.

My problem is I can't simply compile a string without running it. I can do

python -c "print('Hello World')"
for just executing the string where "print('Hello World')" would be a php string variable

but I'm not sure how to simply just check for syntax errors.

I tried
python -m py_compile -c "print('Hello World')"
but it doesn't like that for what looks like the -m on py_compile doesn't like strings, only files

So outside of basically making a new .py file for every string the client sends me and working on that, is there a better way without making new files or making a separate python script to handle this. I'm trying to do this in one php file. This might be a big nono doing python command line scripts on strings so I might as well ask.

Answer Source

You can use the parser-Module. Write a script like this:

import sys
import parser


data = sys.argv[1]

try:
    parser.suite(data)
except SyntaxError as e:
    print(e)

Invoke like this

python3.6 /tmp/test.py "import math"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download