在执行之前,将所有从python脚本触发的shell命令打印到控制台上 [英] Printing all shell commands fired from python script, onto console before executing

查看:85
本文介绍了在执行之前,将所有从python脚本触发的shell命令打印到控制台上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个中等大小的python脚本,它可以从自身内部执行很多shell命令.我想在执行之前将所有这些命令打印到屏幕上,以便可以跟踪python脚本的控制流.

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.

现在,该脚本使用多个命令来实际执行Shell命令,包括os模块中的system()以及子进程模块中的call(),popen()和check_output().这样做最简单的方法是什么?

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?

我在想一个包装函数,该函数在执行前会打印shell命令参数,但是我不知道如何编写一个通用的函数,它可以根据用户的判断调用正确的call/Popen或其他命令.而且我们还必须记住,这些调用采用不同数量和类型的参数.

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.

谢谢!

推荐答案

构建并安装

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:

import os

def log_wrap(f):
    def logging_wrapper(*args, **kwargs):
        print("Calling {} with args: {!r}, kwargs: {!r}".format(f.__name__, args, kwargs))
        return f(*args, **kwargs)

    return logging_wrapper

os.system("echo 'Hello, world!'")
os.system = log_wrap(os.system)
os.system("echo 'How do you like me now?!'")

此代码在运行(python3)时会打印:

This code, when run (python3) prints:

$ python test.py
Hello, world!
Calling system with args: ("echo 'How do you like me now?!'",), kwargs: {}
How do you like me now?!

请注意,在第一次和第二次调用 os.system 的过程中,我将 os.system 函数替换为一个打印日志消息的函数,然后将参数传递给原始功能.您可以将日志消息打印到文件中,或(更好)调用 logging 模块,或调用 pdb 调试器,或任何您喜欢的...

Note that between the first and second calls to os.system, I replaced the os.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 the logging module, or invoke the pdb debugger, or whatever you like...

这篇关于在执行之前,将所有从python脚本触发的shell命令打印到控制台上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆