Search code examples
pythonstdoutsys

Can't seem to write error to output file if a script doesn't run correctly


I've written a function which reads and runs a python script, then sends it's output to a text file. I'm trying to get it to write a simple string, or the error in question, to the text file if the script it ran is broken/doesn't work. Below is the code in question:

                file_dir = a_dir[0]
                file_name = a_dir[1][:-3]
                with open(f'{self.output_directory}\\output_{file_name}.txt', 'w') as f:
                    try:
                        subprocess.call(
                            [sys.executable, file_dir], stdout=f)
                    except:
                        f.write("An error occured with the script")

The first part of it works fine - it does run a functioning file and writes the output.

Do I need to be more specific with the error exception? Any help would be greatly appreciated!


Solution

  • If your code works fine and sys.executable is being run then there will be no exception and so your f.write code won't be run. If there is an error in a program you run using subprocess this doesn't propagate to an exception in a program you run it from. You'd have to know something about this program to know that there was an error you could look at the [returncode][1] from the subprocess.call function call. Another option is that instead of running a new python interpreter you could load the module yourself and then run code from within it using try except blocks. If you can't rely on any structure to the file then you could read the file as text and then run the code within it using eval or exec within a try except structure, that being said if you don't know anything about the file in advance it is likely a massive security flaw for you to be executing it at all let alone within the context of your running application.

    **late edit read the file as text vice test which was a typo [1]: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode