newbie question...

T

trfilmographer

Hi!

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it? like::: python
myfile.py myVar1 myVar2

Thanks!!!
 
T

Tim Chase

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it? like::: python
myfile.py myVar1 myVar2

You're looking for sys.argv:

tim@rubbish:~$ python - one two
Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
[GCC 4.2.4 (Debian 4.2.4-1)] on linux2
Type "help", "copyright", "credits" or "license" for more
information. ['-', 'one', 'two']


-tkc
 
R

r

yes, but your script will need to know hoe to handle this.the
following will open a file who's name was passed to the script

if len(sys.argv) > 1:
try:
open_file(fname=sys.argv[1])
except:
pass
 
T

trfilmographer

yes, but your script will need to know hoe to handle this.the
following will open a file who's name was passed to the script

if len(sys.argv) > 1:
    try:
        open_file(fname=sys.argv[1])
    except:
        pass



ah, ok. now what if I want the variable to be an integer that I
send? for instance if I send 99 to the program, it is picking it up
as a string instead of an integer value. How do I handle this with
python??
 
R

r

i was just giving you an example from my TextEditor.py script.

this is how arg works
lets say you have a script named MyScript.py
---
import sys
print sys.argv
---
call the script with arguments
MyScript.py 99 100
['C:\\Python25\\MyScript.py', '99', '100']


int(sys.argv[1]) -> 99
 
T

Tim Rowe

2008/12/12 said:
ah, ok. now what if I want the variable to be an integer that I
send? for instance if I send 99 to the program, it is picking it up
as a string instead of an integer value. How do I handle this with
python??

As 'r' has said, you can cast it to integer. In the real world you'd
want to handle the case where the user passes in something that isn't
an integer, or passes in nothing at all -- it's generally a good idea
to check anything the user enters for validity. It's possibly too
early for you to try to code it, but it's never too early to start
thinking about what you would /want/ it to do. What do you think it
will do for invalid or no command line arguments at the moment? Try
it!
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top