By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,183 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

using command line arguments

P: 11
Hello again!

I've been trying to make my code more generic, and one of the things I want to do is to use a given file name, which can change (in the command line) instead of using a specific name.
My code looks like:

def func1
bla bla bla

def func2
bla bla bla

main code.

My questions are:
Should I name the main code "main" in order to use sys.argv?
What is the exact syntax of argv? If you want to put the first argument (as in 1, not 0) in a string variable, how do I do that?
Should I import anything, and if so, where should I locate the "import..." line? before all the functions, before the main code etc?

I have tried a python websites, but I can't find answers to those questions.


Thanks
Aug 19 '07 #1
Share this Question
Share on Google+
1 Reply


ilikepython
Expert 100+
P: 844
Hello again!

I've been trying to make my code more generic, and one of the things I want to do is to use a given file name, which can change (in the command line) instead of using a specific name.
My code looks like:

def func1
bla bla bla

def func2
bla bla bla

main code.

My questions are:
Should I name the main code "main" in order to use sys.argv?
What is the exact syntax of argv? If you want to put the first argument (as in 1, not 0) in a string variable, how do I do that?
Should I import anything, and if so, where should I locate the "import..." line? before all the functions, before the main code etc?

I have tried a python websites, but I can't find answers to those questions.


Thanks
There is no need for main (this isn't C) ;). argv is part of the system module so to use it, do something like this:
Expand|Select|Wrap|Line Numbers
  1. import sys
  2. print sys.argv[0] # program name
  3. print sys.argv[1:] # command line arguements; if any
sys.argv is basically a list of what you typed at the command line:
Expand|Select|Wrap|Line Numbers
  1. C:\Documents and Settings\UserName> myprogram.py these are some command line arguments 1 3
  2.  
sys.argv will be:
Expand|Select|Wrap|Line Numbers
  1. ["myprogram.py", "these", "are", "some", "command", "line", "arguments", 1, 3]
  2.  
Aug 19 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.