I have a moderately large python script that executes a lot of shell commands from within itself. I would like to print all these commands to screen before executing it, so that I can trace the control flow of the python script.
Now, the script uses multiple commands to actually execute shell commands, including system() from os module, and call(), popen() and check_output() from subprocess module. What might be the easiest way to do this?
I was thinking of a wrapper function that prints the shell command argument before executing it, but I don't know how to write a generic one that can call the correct call/Popen or other command as per user discretion. And we also have to keep in mind that these calls take in different number and type of arguments.
Thanks!
Since you want to start a child process, but log your behavior, you will need to record child process stdout, stderr,
Suppose you are constructing a command (example, mysqldump) and you have the database, table, and credentials filenames (db, tbl, cnf) loaded. You want to print the command you are about to executed,
Now, assume you have opened output and error files above (ofd, efd),
Remember to close ofd, efd.
Build and install a decorator for the various calls you wish to intercept. Because even the "builtin" functions are first-class objects, you can replace them with logging versions:
This code, when run (python3) prints:
Note that between the first and second calls to
os.system
, I replaced theos.system
function with one that prints a log message before passing the arguments along to the original function. You can print your log message to a file, or (better yet) call thelogging
module, or invoke thepdb
debugger, or whatever you like...