HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

CLI Twitter client in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythontwitterclientcli

Problem

Here is a simple client for Wwitter that I wrote based on the twitter library in Python. The aim is to be able to read the feeds from different twitter accounts from the same place in a light way.

I should mention that the code does what I want it to do. Nevertheless, how could I improve it?

(It is available on GitHub.)

```
#!/usr/bin/python

import sys
import os
import getopt
from twitter import *

# Default values
def_counts = 10
users = []
dir_creds = "./data/oauth/"

# input parameters
def usage():
print "Run: " + sys.argv[0] + " [OPTIONS]"
print "Where OPTIONS is one the following: "
print " -h --help"
print " -c N --counts=N"
print " -u \"name\" --user=\"name\""
print " -a --all"
print " -l --list"

def main(argv):
global def_counts, users
try:
opts, args = getopt.getopt(argv,"hc:u:al",["help","counts=","user=","all","list"])
except getopt.GetoptError:
usage()
exit(2)
for opt,arg in opts:
if opt in ["-h","--help"]:
usage()
exit(1)
elif opt in ["-c","--counts"]:
print "Retrieving "+str(arg)+" tweets."
def_counts = arg
elif opt in ["-u","--user"]:
print "User: "+arg
users.append(arg)
elif opt in ["-a","--all"]:
print "all users"
if os.path.exists(os.path.expanduser(dir_creds)):
token_files = filter(lambda x: x.endswith('.token'), os.listdir(os.path.expanduser(dir_creds)))
for file in token_files:
usr = file[:file.index(".token")]
users.append(usr)
else:
print "No user to be added, path undefined"
exit(2)
elif opt in ["-l","--list"]:
if os.path.exists(os.path.expanduser(dir_creds)):
token_files = filter(lambda x: x.endswith('.token'), os.listdir(os.path.expanduser(dir_creds)))
for file in token_files:
usr = file[:file.index(".token")]
print usr
else:
print "Got the following and I don't know what to do with it:"
print opt + " " + arg
usa

Solution

For starters using Python 3 or at least being compatible with it would
be a good idea. Meaning that all the print calls should be using the
function form, i.e. print(...).

Next, take a look at PEP8
and use four spaces for indentation.

Parsing command line arguments is a bit nicer with
argparse, but since
you're already done with it it might not make too much sense to rewrite
that part.

There's duplicated for the "--all" and "--list" cases that would be
better served with a common function.

The colour definitions can be taken from some module, e.g. take a look
at termcolor or
colorama.

Lastly the for c in range(len(data)): will always be a pattern that
should be replaced with direct iteration, i.e. for x in data:. The
line is also way to long to read it easily.

Context

StackExchange Code Review Q#122449, answer score: 3

Revisions (0)

No revisions yet.