[PYTHON] Tips for replacing and debugging functions

When you write a little script, you assemble and execute a string, right?

Something like this (I don't use shutil because it's an example)

os.system('mv %(src)s %(dst)s' % locals())

Such a guy

os.system('ssh %(user)s@%(host)s -p %(port)s hostname' % locals())

So, have you ever done this when you want to check the assembled string? It's a hassle

# os.system('mv %(src)s %(dst)s' % locals())
print 'mv %(src)s %(dst)s' % locals()

If you want to debug like this, it's easier to replace ʻos.system`

def out(s):
  print s

os.system = out
os.system('mv %(src)s %(dst)s' % locals())

Now that ʻos.systemis actuallyprint`, when you run it, the assembled string will be output as standard and you can debug it easily.

By the way, python2 series uses def because print is a sentence, but python3 series is easier because print is an expression.

os.system = print
os.system('mv %(src)s %(dst)s' % locals())

If it is a first-class object language, it will be applied, so it may be good to remember

Recommended Posts

Tips for replacing and debugging functions
6 Python libraries for faster development and debugging
[Python for Hikari-] Chapter 06-04 Functions (arguments and return value 3)
Python and numpy tips
Higher-order functions and decorators
[Python for Hikari-] Chapter 06-01 Functions (Intrinsic Functions and Function Definitions)
Debugging and testing reports
[Python for Hikari-] Chapter 06-03 Functions (arguments and return value 2)
Anonymous and map functions
Tips for coding short and easy to read in Python
[Statistics for programmers] Random variables, probability distributions, and probability density functions
[Python for Hikari-] <Supplement> Chapter 06-05 Functions (arguments and return values 4)
This and that for using Step Functions with CDK + Python
Splitting re.split and replacing re.compile
Keyword arguments for Python functions
Python for super beginners Python #functions 1
[Python + Selenium] Tips for scraping
Python 3 sorted and comparison functions
Class inheritance and super functions
~ Tips for beginners to Python ③ ~
Introduction and tips of mlflow.Tracking
Tips for data analysis ・ Notes