воскресенье, 27 мая 2012 г.

command line options

There is useful foo in C which can parse command line options. Just like when user writes
user#pc: ls -la
Here is the detail description:

In Python there is just the same foo:

And one more useful link with tips and tricks for Python:
http://www2-pcmdi.llnl.gov/cdat/tips_and_tricks/python_tips/index_html



#!/usr/bin/python
import getopt
import sys
import multiprocessing
import threading
import time
multi_line_help = """
Usage: args.py [OPTIONS]
args.py is an example of command line parameters usage
options:
-h --help\tprints this help
-p --process\tstarts N process and prints \
 \"hello from proc\" from each one
-t --threads\tstarts N threads and prints \
 \"hello from thread\" from each one"""


def printMultilineHelp():
print multi_line_help

def printHelp():
print "Usage: args.py [OPTIONS]"
print "args.py is an example of command line parameters usage"
print "options:"
print "-h --help", "\t", "prints this help"
print "-p --process", "\t", "starts N process and prints \ \"hello from proc\" from each one"
print "-t --threads", "\t", "starts N threads and prints \ \"hello from thread\" from each one"

def processCall():
p = multiprocessing.current_process()
print "hello from process:", p.name, "id:", p.pid
while True:
time.sleep(1)

def threadCall():
t = threading.currentThread()
print "hello from thread:", t.getName()


options, remainder = getopt.getopt(sys.argv[1:], 'hp:t:',
["help", "process=", "threads="])
            
num_threads = 0
num_process = 0
# if you need to handle exact one option in time, use switch
# or use one function to handle and than sys.exit()
            
if options == []:
printMultilineHelp()
sys.exit()
            
for opt, arg in options:
print "options:", opt, "arguments", arg
if opt in ("-h", "--help"):
printHelp()
sys.exit()
elif opt in ("-p", "--process"):
num_process = int(arg)
print 'Start', num_process, 'process'
elif opt in ("-t", "--threads"):
num_threads = int(arg)
print 'Start', num_threads, 'thread'

process_jobs = []
threads_jobs = []
if num_process != 0:
p = multiprocessing.current_process()
print "Caller process name:", p.name, "id:", p.pid
for i in range(num_process):
j = multiprocessing.Process(target=processCall, \
      name = 'process_' + str(i))
# use if you don't want to wait  
  # for completion and do another stuff
j.daemon = True
process_jobs.append(j)
j.start()
#j.join()
print process_jobs[:]


if num_threads != 0:
for i in range(num_threads):
j = threading.Thread(name = "thread_" + str(i), \
      target = threadCall)
# use if you don't want to wait 
  # for completion and do another stuff
#j.daemon = True
threads_jobs.append(j)
j.start()
j.join()
print threads_jobs[:]

# now when parrent stops, all childs stops too
#while True:
# time.sleep(1)


Based on:
http://www.doughellmann.com/PyMOTW/contents.html

Комментариев нет:

Отправить комментарий