Search code examples
pythonmethodsargumentslinecode-duplication

Keeping code DRY when repeatedly referring to command-line options' configuration


I just got a Raspberry Pi, and I'm building a Reddit API-based application for it, using the PRAW library. I'm executing my python files by using:

sudo python3 main.py

However, I would like to pass arguments to this file from the command line (so I can run the app silently by passing it the argument silent for example), and I know I can do so with sys.argv[0], sys.argv[1], etc...

My problem is how to do this while following DRY -- Don't Repeat Yourself -- in referring to the configuration established by those options.

This is a portion of my code:

def init():
if (len(sys.argv) >= 1):
    global semisilent
    global silent
    for arg in sys.argv:
        if arg == "semisilent":
            semisilent = True
        if arg == "silent":
            silent = True

print ("--------[ Reddipi v0.1 ]--------\n")

if silent:
    print ("   ++Running in silent mode++   \n")
elif semisilent:
    print ("++Running in semi-silent mode++ \n")
else:
    print ("      Logging in to reddit      ")
    print ("              ....              ")
global r
r = oauth.login()

if not silent:
    print ("        Login successful        \n")

if not silent and not semisilent:
    print ("     Connecting to database     ")
    print ("              ....              ")
db.init(tablename)
if not silent:
    print ("     Connection successful      \n")

if not silent and not semisilent:
    global sub_name
    q_sub = input("      Use custom subreddit?     \n")
    if (q_sub[0]=="y"):
        q_sub = input("     Enter custom subreddit:    \n")
        if ((len(q_sub)==0) or (q_sub==" ")):
            print ("  No valid input. Using default \"" + sub_name + "\" \n")
        else:
            sub_name = q_sub
            print ("\r   Using subreddit \"" + sub_name + "\"\n")
    else:
        print ("        Using default \"" + sub_name + "\"    \n")

I find myself making the code very hard to read by constantly putting if not silent and such before other pieces of code. I've also thought about having multiple methods with the same essential functions but with code left out if the user had put in silent or semisilent, but this would lead to unnecessary code duplication.

Is there another / a good way to change the behaviour of my methods without having to make it unreadable or rewrite the code multiple times?

Thanks a lot for the help! - Jeroen


Solution

  • Define your own custom "print" method, which checks if some variable (silent) is set, and then skips printing it if that value is set. So all your lines print('value') will turn into something like myprint('value'). I personally like using the function names verbose() and debug() and having two log levels. In your case, maybe call them "silent()" and "semisilent()" or something.