1

I want to pass a value into my python script, as shown in the below image

enter image description here

Where, xyz would be my python file which requires the abc value.

How do I do this and access the abc value in xyz.py?

1
  • 2
    u should use str(sys.argv) before that user import sys Commented Mar 24, 2014 at 8:17

3 Answers 3

1

You can try like this,

#!/usr/bin/python

import sys

print 'Argument List:', str(sys.argv)
Sign up to request clarification or add additional context in comments.

Comments

1

you can use sys.argv but better approach is to use argparse module.

here is an example.

#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser(prog='reader', description='Read commandline value.')
parser.add_argument('-v', '--value')
args = parser.parse_args()
print "Value you entered: %s" % args.value

2 Comments

Why is argparse a better method? Can you please explain?
@Zedai : sorry for late reply, have a look at this argparse vs sys.argv and this too, using argparse in conjunction with sys.argv I hope this helps.
1

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purpose:

sys.argv is the list of command-line arguments.

len(sys.argv) is the number of command-line arguments.

Example: Consider the following script test.py:

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

Now run above script as follows:

$ python test.py arg1 arg2 arg3

This will produce following result:

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

command line arguments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.