0

I had made a text editor, and added a run command to it. So recently I am using exec() to execute commands but with big code it shows error. I want to make a run command like a build command in sublime text for my text editor. So how can I make a function to perform this program execution.

It will be better if the function tell me the error too , like an any modern compiler does.

Kumar Saptam
  • 358
  • 4
  • 11
  • Check the accepted answer at https://stackoverflow.com/questions/706989/how-to-call-an-external-program-in-python-and-retrieve-the-output-and-return-cod – Kenly Feb 11 '19 at 11:33
  • Possible duplicate of [How to call an external program in python and retrieve the output and return code?](https://stackoverflow.com/questions/706989/how-to-call-an-external-program-in-python-and-retrieve-the-output-and-return-cod) – Tobias Brösamle Feb 11 '19 at 11:43

1 Answers1

1

You could store the code inside a file and then call execute it with Popen.
This allows you to get the output of stdout and stderr.

Error output goes into stderr.
And normal output e.g. print goes into stdout

from subprocess import (
    Popen,
    PIPE,
)

python_cmd = Popen(('python3', 'test.py'), stderr=PIPE, stdout=PIPE)
output = python_cmd.communicate()
stdout = output[0].decode()
stderr = output[1].decode()
Manuelraa
  • 36
  • 4
  • I am getting error that file not found default_compiler_location=open('defaultCompilerDist.py','w+') default_compiler_location.write(str(txt.get("1.0", "end-1c"))) default_compiler_location.close() default_compile_chr=py_compile.compile('defaultCompilerDist.py') executedScript=Popen(['python3','defaultCompilerDist.py'], stderr=PIPE,stdout=subprocess.PIPE).communicate() output = executedScript.communicate() stdout = output[0].decode() stderr = output[1].decode() run_shell_text.insert(END,str(stdout)) – Kumar Saptam Feb 13 '19 at 13:27
  • The file ("defaultCompilerDist.py") is in the same folder of the main program. – Kumar Saptam Feb 13 '19 at 13:28
  • As far as I can see it should find the file. You write the file. I dont know the purpose of using py_compile on it before using Popen. Also remove the .comunicate() after Popen because you are doing that already one line under it – Manuelraa Feb 14 '19 at 14:29
  • i used py_compile.compile so that i can find any error in the code. – Kumar Saptam Feb 15 '19 at 12:32
  • I cannot give input and cannot see time sleeps in my code. For example if I add time.sleep(3) in a code then by running it the whole output appears after 3 second. Can I get sleeps in my output. – Kumar Saptam Mar 25 '19 at 09:24
  • 1
    how can I get the error line number or the line number which is showing error show that I can add a tag and highlight it? – Kumar Saptam May 15 '19 at 16:10