Receita: Entrada de parâmetros pela linha de comando
Há duas formas de se passar parâmetros pela linha de comando, uma pelo módulo optparse e outra pelo sys.argv, veja as duas:
1 #!/usr/bin/python
2 # Rod Senra 2005
3 # This code is in the public domain.
4 # Quick, rough, ugly and dirty holiday hack, not robust at all!
5
6 # Uso:
7 # $ python translate.py paz pt-br en
8 # peace
9 #
10
11 import sys
12 from urllib2 import urlopen, Request
13 from string import Template
14
15 # Not in stdlib, but handy for
16 # quick&dirty hacks like this
17 from BeautifulSoup import BeautifulSoup
18
19 # Some google magic spells
20 google_template = Template("http://translate.google.com/translate_t"\
21 "?text=$word&langpair=$from_lang%7C$to_lang"\
22 "&hl=en&ie=$encoding")
23
24 # extremely user-enemy interface
25 # people can improve on this with their
26 # optparse knowledge. I'm not in the mood right now ;o)
27 params={'word':sys.argv[1].strip(),
28 'from_lang':sys.argv[2].strip(),
29 'to_lang':sys.argv[3].strip(),
30 'encoding':'ISO-8859-15'}
31
32 query_url = google_template.substitute(params)
33
34 req = Request(query_url)
35
36 # I had to lie here to be accepted, did not bothered
37 # to explore further ;o)
38 req.add_header('User-Agent','User-Agent: Mozilla/5.0')
39 req.add_header('Accept','text/xml,application/xml,application/xhtml\
40 +xml,text/html,text/plain')
41 req.add_header('Accept-Encoding','identity')
42 req.add_header('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7')
43 req.add_header('Connection','keep-alive')
44
45 page = urlopen(req)
46 page_result = page.read()
47 # print page.headers, page_result
48
49 # get the beef ;o)
50 soup = BeautifulSoup()
51 soup.feed(page_result)
52 beef = soup.first('textarea')
53 translated = beef.contents[0].string
54 print translated
1 #!/usr/bin/python
2
3 # Uso:
4 # $ python parametros.py -o argumento_requerido
5 # teste
6 #
7
8 from optparse import OptionParser
9
10 def main():
11 parser = OptionParser()
12
13 parser.add_option("-f", "--arquivo", help="Imprime em arquivo")
14 parser.add_option("-q", "--silencia", help="Não imprime a mensagem de saída")
15 parser.add_option("-o", "--saida", help="Imprime a mensagem de saída")
16
17 (options, args) = parser.parse_args()
18
19 if options.arquivo:
20 import codecs
21 f = codecs.open('optparse_teste.txt', 'a', 'utf-8')
22 f.write("teste")
23 f.close()
24
25 if options.silencia:
26 print ("")
27
28 if options.saida:
29 print ("teste")
30
31 if __name__ == "__main__":
32 main()
Volta para CookBook.