optparse global

A

ashtonn

Hello,

How do i make an option passed through command line, using optparse
global. I need to import this value in another file.

This is what iam trying to do.

$python test.py -d ffffffffffff

i should be able to store 'ffffffffffff' as global so that i could
access this value in another file. If 'ffffffffffff' is not given, then
a default value stored in
parser.add_options("-d", default="01ff010BFFFF", action="store")
will be returned.

Thanks,
-Ashton
 
S

Skip Montanaro

Ashton> How do i make an option passed through command line, using
Ashton> optparse global. I need to import this value in another file.

Place the parser's output at the module scope.

global options
parser = OptionParser()
parser.add_option("-p", "--port", dest="port", default=5007,
type="int",
help="port to connect to for remote interpreter")
...
options, args = parser.parse_args()

The user of your module can then execute

from othermodule import options
print options.port

Skip
 
A

ashtonn

This does not seem to work. I still get the default value 5007 when i
run
$python txd.py - p5006
$python testme.py

***txd.py***

global options
parser = OptionParser()
parser.add_option("-p", "--port", dest="port", default=5007,
type="int",
help="port to connect to for remote interpreter")

options, args = parser.parse_args()

**testme.py**
from txd import options

print options.port

-Ashton
 
S

Skip Montanaro

Ashton> This does not seem to work. I still get the default value
Ashton> 5007...

Hmmm... Works for me (Python from CVS):

% python testme.py
5007
% python testme.py -p 5006
5006
% python testme.py -p5006
5006

The only change from what you posted was to add

from optparse import OptionParse

to txd.py.

Skip
 
D

Dennis Lee Bieber

Thanks. It works.
-Ashton

So far as I understand, the

global

is not needed for your example. "global <name>", when used
/inside/ a function definition, grants modify access to <name> at the
module level.

But for an "import module", you already specify as module.name
to access the module level namespace.

--
 
S

Skip Montanaro

Dennis> So far as I understand, the
Dennis> global
Dennis> is not needed for your example.

I think the original context was that optparse was being used in the context
of a function.

Skip
 

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
474,239
Messages
2,571,200
Members
47,838
Latest member
elibuskamoSeAve

Latest Threads

Top