how to(can we ?) pass argument to .py script ?

Q

quiteblack

howdy~

i wrote a .py file and it works fine, my goal is to pass argument to
that py file when it get executed, and accept that argument within py
file, eg. i prefer a command like below:

python test.py -t

and then, i may get "-t" within test.py for later use.

i have no ideas how to do and i'm really stuck, can anyone help ?
 
S

Simon Brunning

i wrote a .py file and it works fine, my goal is to pass argument to
that py file when it get executed, and accept that argument within py
file, eg. i prefer a command like below:

python test.py -t

and then, i may get "-t" within test.py for later use.

i have no ideas how to do and i'm really stuck, can anyone help ?

Short answer:

import sys
print sys.argv

You might also want to take to butchers at the optparse module.
 
B

billie

It's quite simple. If this usage example can helps you...

### parser
try:
opts, args = getopt.getopt(sys.argv[1:], "h, e, p:", ["help"])
mode = 'reply' # default mode
pwd = ' ' # default pass (blank)
for o, a in opts:
if o == '--help' or o == '-h':
print helper()
os._exit(0)
if o == '-h':
print helper()
os._exit(0)
if o == '-e':
mode = 'echo/reply'
if o == '-p':
pwd = a
if len(args) < 3 :
print " ERR: Too much few arguments.\n Type %s -h for help." \
%(sys.argv[0])
os._exit(0)
if len(args) > 3:
print \
" ERR: Too much arguments.\n Type -h and \
look example to send argumented commands."
os._exit(0)
except:
print " ERR: Invalid Option.\n Type %s -h for help." \
%(sys.argv[0])
os._exit(0)
### /parser
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,342
Members
48,018
Latest member
DelilahDen

Latest Threads

Top