473,485 Members | 1,393 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Noob question regarding sys.argv[]

TMS
119 New Member
I'm completely new to Python, never wrote a C program, but I have written in C++. I've never used argv, but an assignment is requiring me to learn it and use it now. I'm using Python 2.5, IDLE (for writing code), using Win XP pro environment (can't get my Ubuntu to see my wireless card).

I'm supposed to write a module that will take an argument from the command line that will read a file and process it. I really don't know how to do this and would appreciate a spoon fed version tutorial.

Help, Please?
Jan 15 '07 #1
11 8754
bartonc
6,596 Recognized Expert Expert
I'm completely new to Python, never wrote a C program, but I have written in C++. I've never used argv, but an assignment is requiring me to learn it and use it now. I'm using Python 2.5, IDLE (for writing code), using Win XP pro environment (can't get my Ubuntu to see my wireless card).

I'm supposed to write a module that will take an argument from the command line that will read a file and process it. I really don't know how to do this and would appreciate a spoon fed version tutorial.

Help, Please?
in a file (say myModule.py)
Expand|Select|Wrap|Line Numbers
  1. import sys
  2. for arg in sys.argv:
  3.     print arg    # the zeroth element is the module name
  4. raw_input("press any key")    # a trick to keep the python console open
(of course python must be in PATH e.v.)
from the command line (IDLE won't do this) type

python myModule.py any number of args

The raw_input() call is not needed if your command-line console does not invoke a separate window for the python process (the way that Start->Run does).
Jan 15 '07 #2
TMS
119 New Member
ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

python myModule.py file.txt

should call the module to call the text file, right?

I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.
Jan 15 '07 #3
ghostdog74
511 Recognized Expert Contributor
ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

python myModule.py file.txt

should call the module to call the text file, right?

I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. import sys
  3. print "script name is: ", sys.argv[0]
  4. print "first argument file name is: " , sys.argv[1]
  5. filename = sys.argv[1] #define the file name
  6. data = open( filename ) .read() #read everything in file into memory
  7.  
Jan 15 '07 #4
bartonc
6,596 Recognized Expert Expert
ok, so say my file name is file.txt (should it be formatted differently, like .py?). That is my arg, right? so:

I appreciate your patience. I've been trying to work this out all day, and I know it should be obvious, but for some reason it isn't.
Ok, let's go slowly here... The file with your python program in it (often called a "script") gets the .py extension for many reasons:
1) This is the standard thing to do.
2) IDLE will to automatic indentation and checking, colorizing and syntax checking.
3) Windows will launch .py files using python (with no arguments).

python myModule.py file.txt

should call the module to call the text file, right?
Here, the idea of "calling" file.txt isn't quite right. Python gets "called" with arguments. The first argument is the module to run and its name can be accessed by sys.argv[0]. Arguments coming after that are simply stored in sys.argv[1:] for the script to access as it needs. So, as ghostdog shows, if it is the name of a file, that file can be "opened" from within the script.
That said, I'll modify my earlier program considering that sys.argv[0] is actually an argument to python and everthing after that (on the command line) is meant for your script.
Expand|Select|Wrap|Line Numbers
  1. # file: PyTest1.py
  2. import sys    # need to import the sys library module
  3. for arg in sys.argv[1:]    # a 'slice' prevents index errors
  4.     print arg    # these will be all of the space-separated text on the command line
  5. raw_input("press any key")
Jan 15 '07 #5
TMS
119 New Member
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. import sys
  3. print "script name is: ", sys.argv[0]
  4. print "first argument file name is: " , sys.argv[1]
  5. filename = sys.argv[1] #define the file name
  6. data = open( filename ) .read() #read everything in file into memory
  7.  

this is so embarrassing... OK, I'm at the command line. I've got a module named myModule.py. In it I have a combination of the previous replies to my question and they are:

Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. for arg in sys.argv:
  4.     print arg    
  5.  
  6. print "script name is: ", sys.argv[0]
  7. print "first argument file name is: " , sys.argv[1]
  8. filename = sys.argv[1]
  9. data = open( filename ) .read()
  10. raw_input("press any key")    # a trick to keep the python console open
  11.  
  12.  
I go to command line, type the following:

python myModule.py someFile.txt
I get the following:
File "<stdin>", line 1
python myModule.py.py

SyntaxError: invalid syntax

What am I doing wrong... I hate being such a noob.
Jan 15 '07 #6
bartonc
6,596 Recognized Expert Expert
this is so embarrassing... OK, I'm at the command line. I've got a module named myModule.py. In it I have a combination of the previous replies to my question and they are:

Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. for arg in sys.argv:
  4.     print arg    
  5.  
  6. print "script name is: ", sys.argv[0]
  7. print "first argument file name is: " , sys.argv[1]
  8. filename = sys.argv[1]
  9. data = open( filename ) .read()
  10. raw_input("press any key")    # a trick to keep the python console open
  11.  
  12.  
I go to command line, type the following:

python myModule.py someFile.txt
I get the following:
File "<stdin>", line 1
python myModule.py.py

SyntaxError: invalid syntax

What am I doing wrong... I hate being such a noob.
The problem is that you are in the Python sell, not a DOS command line.
I'd also recommend that you proceed more slowly. For example, the code I gave doesn't require any error protection. The syntax anyList[1] will cause and error if there are less than two elements in the list. Python has cool ways of dealing with this, but you are not at this stage yet (but you will be very soon).
Jan 15 '07 #7
dshimer
136 Recognized Expert New Member
Let me say right off that this isn't 100% relevant so should probably be ignored until the argv questions are worked out, but for future reference it seems a reasonable place to put it in.
Originally coming from a C/C++ background I found that many programs I was re-writing wanted a reference to argc. I found it easiest to take the equivilent code and make one.

Expand|Select|Wrap|Line Numbers
  1. def argc():
  2.     '''
  3.     Should be the equivalent of the c style argc.
  4.     '''
  5.     return len(sys.argv)
  6.  
Jan 15 '07 #8
ghostdog74
511 Recognized Expert Contributor
Expand|Select|Wrap|Line Numbers
  1. def argc():
  2.     '''
  3.     Should be the equivalent of the c style argc.
  4.     '''
  5.     return len(sys.argv)
  6.  
does the C++ argc mean the number of arguments? if it is, then the above
might be
Expand|Select|Wrap|Line Numbers
  1. return len(sys.argv[1:])
  2.  
because sys.argv[0] is the script name.
Jan 15 '07 #9
dshimer
136 Recognized Expert New Member
Yeah, but if I remember right, like python, argv[0] is always the name of the command, so argc was always one off the number of actual argurments passed. So to keep things consistant in my mind, and in the ported code, I just kept the return value the same as it would have been.

There is no real reason to use this instead of the actual len command, it was just something I noticed early on, and mention for those coming from that background that are looking for argc or in this case the equivalent.

does the C++ argc mean the number of arguments? if it is, then the above
might be
Expand|Select|Wrap|Line Numbers
  1. return len(sys.argv[1:])
  2.  
because sys.argv[0] is the script name.
Jan 15 '07 #10
TMS
119 New Member
Ok, forgive my excitement, but... YEAH!!!! It works.

Thank you very much
Jan 15 '07 #11
bartonc
6,596 Recognized Expert Expert
Ok, forgive my excitement, but... YEAH!!!! It works.

Thank you very much
... YEAH!!!! It works... Believe me, we all share your exitement! Keep posting, Barton
Jan 15 '07 #12

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

Similar topics

42
3382
by: Holger | last post by:
Hi guys Tried searching for a solution to this, but the error message is so generic, that I could not get any meaningfull results. Anyways - errormessage:...
10
1876
by: sam_cit | last post by:
Hi Everyone, I had a doubt regarding extern decleration, i tried this is one source file, extern int sample; extern int sample; int main() {
8
2017
by: sore eyes | last post by:
Hi I just downloaded the free Watcom compiler and am having a little trouble with File IO http://www.openwatcom.org/index.php/Download I downloaded the following example, commented out the...
2
1150
by: Logan | last post by:
(CODE I) #include <stdio.h> int main(int argc, char *argv) { int x; printf("argc = %d\n", argc); for(x = 0; x < argc; x++ ) { printf("argv = %s.\n", x, argv);
0
7090
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7116
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7161
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6825
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5418
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4551
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3058
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3063
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.