473,224 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,224 software developers and data experts.

Passing parameters at the command line (New Python User)

Hi there. I just wondered whether anyone could recommend the correct
way I should be passing command line parameters into my program. I am
currently using the following code:

def main(argv = None):
file1= "directory1"
file2 = "directory2"
if argv is None:
args = sys.argv[1:]

if len(args) == 0:
Initialise.init(0)
Process.processCon(file1, 0)
Output.print()

for i in range(len(args)):
if args[i] == "-no":
Initialise.init(0)
Process.processCon(file2,1)
Output.print()

if args[i] == "-not":
Initialise.init(1)
Process1.process(stepStore, firstSteps)
Output.print1()

if __name__ == "__main__":
main()
Have I used bad syntax here so that a user can either run the program
with commands:
main.py
main.py -no
main.py -not

If I also wanted an option file to be passed in at the command line
for 'main.py' and 'main.py -no' what would be the best way to go about
this? I have never used Python to pass in arguments at the command
line so any help would be much appreciated.

Cheers
Chris

Sep 24 '07 #1
4 5470
cj***@bath.ac.uk wrote:
Hi there. I just wondered whether anyone could recommend the correct
way I should be passing command line parameters into my program. I am
currently using the following code:
<snip/>

Use the module optparse.

Diez
Sep 24 '07 #2
cj***@bath.ac.uk writes:
I have never used Python to pass in arguments at the command line so
any help would be much appreciated.
Your 'main()' approach is good. I'd rather have the function require
an 'argv' parameter, and have the default set only in the 'if __name__
== "__main__":' block, since that fits my ideas better about the
defaults.

def main(argv):
parse_commandline(argv)
do_cool_stuff()

if __name__ == "__main__":
from sys import argv
main(argv)

I also tend to catch SystemExit in the function, so the exit code can
be returned instead of raised; but that's outside the scope of this
thread.

For anything more advanced than unconditionally grabbing arguments in
sequence from the command line, you should investigate the 'optparse'
module <URL:http://docs.python.org/lib/module-optparsefrom the
standard library.

--
\ "Holy knit one purl two, Batman!" -- Robin |
`\ |
_o__) |
Ben Finney
Sep 24 '07 #3
On Mon, 24 Sep 2007 01:04:58 -0700, cjt22 wrote:
for i in range(len(args)):
if args[i] == "-no":
Initialise.init(0)
Process.processCon(file2,1)
Output.print()

if args[i] == "-not":
Initialise.init(1)
Process1.process(stepStore, firstSteps)
Output.print1()
That ``for`` loop is an anti-pattern in Python. If you want to iterate
over the elements of `args` the just do it directly instead of using an
index:

for arg in args:
if arg == '-no':
# ...

If you need the element *and* an index:

for i, arg in enumarate(args):
# ...

Ciao,
Marc 'BlackJack' Rintsch
Sep 24 '07 #4
cj***@bath.ac.uk wrote:
Hi there. I just wondered whether anyone could recommend the correct
way I should be passing command line parameters into my program. I am
currently using the following code:

def main(argv = None):
file1= "directory1"
file2 = "directory2"
if argv is None:
args = sys.argv[1:]

if len(args) == 0:
Initialise.init(0)
Process.processCon(file1, 0)
Output.print()

for i in range(len(args)):
if args[i] == "-no":
Initialise.init(0)
Process.processCon(file2,1)
Output.print()

if args[i] == "-not":
Initialise.init(1)
Process1.process(stepStore, firstSteps)
Output.print1()

if __name__ == "__main__":
main()
Have I used bad syntax here so that a user can either run the program
with commands:
main.py
main.py -no
main.py -not

If I also wanted an option file to be passed in at the command line
for 'main.py' and 'main.py -no' what would be the best way to go about
this? I have never used Python to pass in arguments at the command
line so any help would be much appreciated.
A solution using argparse (http://argparse.python-hosting.com/):

import argparse

def main(no=False, nott=False):
file1 = "directory1"
file2 = "directory2"

if nott:
print 'Initialise.init(1)'
print 'Process1.process(stepStore, firstSteps)'
print 'Output.print1()'
else:
print 'Initialise.init(0)'
if no:
print 'Process.processCon(file2, 1)'
else:
print 'Process.processCon(file1, 0)'
print 'Output.print()'

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-no', action='store_true')
parser.add_argument('-not', action='store_true', dest='nott')
args = parser.parse_args()
main(no=args.no, nott=args.nott)

Note that I've used print statements since I don't have your Initialize,
Process, etc. objects. If I knew what "-no" and "-not" meant better, I
could give you a better suggestion, e.g. where you parse the 0 or 1
value for Initialize.init directly from the command line.

STeVe
Sep 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: John Leslie | last post by:
I am porting a script from Korn Shell to python and want to pass named parameters like -JOB 123456 -DIR mydir I can get it to work passing --JOB and --DIR but not -JOB and -DIR Any ideas? ...
1
by: Casey Bralla | last post by:
I've got a python cgi-bin application which produces an apache web page. I want to pass arguments to it on the URL line, but the parameters are not getting passed along to python properly. I've...
17
by: Freeserve | last post by:
Hi, I am trying to pass a value from an ASP script to a VB application running on the server. The only way I have got this to work is by using a file, which is too slow. I tried using DDE but...
0
by: Keith Wall | last post by:
Is there any way to pass mysql user variables on the command line? I'd like to do this to enable me to parameterised a mysql script. I'd like to be able to use a command line such as: mysql...
3
by: AndyDunning | last post by:
Hello, I'm interested in establishing the best way to pass information between a vb script and a .net application. We have a VbScript that runs on a users pc every time a phone call is routed...
4
by: Mike Dinnis | last post by:
Hi, I've been working through a number of turorials to try to learn more about retrieving data from a SQL database. I think i've mastered techniques where i create a sql string in the page and...
3
by: Brian Foree | last post by:
I am developing an ASP.NET application that uses Access 2000 as its backend, and have just started getting the following error on 2 ASP.NET pages that had been working until late last week (and I...
7
by: Leo Breebaart | last post by:
I have another question where I am not so much looking for a solution but rather hoping to get some feedback on *which* solutions people here consider good Pythonic ways to approach a issue. ...
2
by: william.w.oneill | last post by:
I have an application that takes a few command line parameters. As recommended by others in this group, I'm using a named mutex to ensure that only one instance of the application is running. My...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.