Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I pass a big string as a single argument?

I'm trying to pass an entire string as an argument to a python script. The problem I am having is that the Python assumes that I only want the first word of the string.

In the example below, the -l arg stands for log and I want it to capture the entire string.

example:

python myscript.py -l "Big String I want to as single argument"

code below:

try:
  opts, args = getopt.getopt(sys.argv[1:], 'hcrn:l:wo:a:emi', ["reset="])
  #-l is one of many arguments I'm looking for
except getopt.error, err:
  print str(err)
  sys.exit(2)

for o, a in getopts:
    if o in ("-l", "--log"):  #log
    logIt(a)  # Problem here a='Big'

How do I get the entire string for the first argument, not just the first word? Example please.

like image 959
codingJoe Avatar asked Apr 24 '26 16:04

codingJoe


2 Answers

First: getopt is pretty outdated and deprecated.

Please use the optparse module of Python or the even newer argparse module (there is a backport of argparse for Python 2.X on PyPI).

The first example clearly covers your usecase solved using optparse:

http://docs.python.org/library/optparse.html

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")

(options, args) = parser.parse_args()

Your code works perfectly given you correct it.
The problem is probably in your logIt function. If I correct this (it actually does not work in its posted form):

for o, a in getopts:
    if o in ("-l", "--log"):  #log
    logIt(a)  # Problem here a='Big'

with this (and using print):

for o, a in opts:
    if o in ("-l", "--log"):  #log
        print a  # No Problem here a=["Big String I want to as single argument"]

it prints what is should print:

C:\Python26>python myscript.py -l "Big String I want to as single argument"
Big String I want to as single argument

So probably your problem is not with getopt but with your logIt function.

like image 23
joaquin Avatar answered Apr 26 '26 05:04

joaquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!