Tyler Liu
Tyler Liu

Reputation: 20356

python sys.argv differentiate int and string

Simply put, how can I differentiate these two in test.py:

python test.py 1
python test.py '1'

Workaround is OK.


Edit:

  1. This workaround looks cool but too complex: argparse
  2. Let the invoker specify args later, in python code use arg = input('Please enter either an integer or a string')
  3. And other workarounds as presented in the answers of this question.

Thank you all for the replies. Every body +1.

Upvotes: 2

Views: 12866

Answers (6)

vikram360
vikram360

Reputation: 161

I'm not sure how correct I am, but if you're using only integer command line arguments, you can typecast it to be int.

suppose (in *nix), I run my program as:

./test.py 1

I can in my program say something line

import sys
def main():
  a=int(sys.argv[1])

Upvotes: 0

hamstergene
hamstergene

Reputation: 24429

Windows-specific:

# test.py
import win32api
print(win32api.GetCommandLine())

Example:

D:\>python3 test.py 3 "4"
C:\Python32\python3.EXE  test.py 3 "4"

You can then parse the command line yourself.

Upvotes: 2

Rosh Oxymoron
Rosh Oxymoron

Reputation: 21055

The shell command line doesn't support passing arguments of different types. If you want to have commands with arguments of different types you need to write your own command line or at least your own command parser.

Variant 1:

Usage:python test.py "1 2 '3' '4'"

Implementation:

command = sys.argv[1]
arguments = map(ast.literal_eval, command.split())
print arguments

Variant 2:

Usage:

python test.py
1 2 '3' 4'
5 6 '7' 8'

Implementation:

for line in sys.stdin:
    arguments = map(ast.literal_eval, line.split())
    print arguments

(Of course, you'd probably want to use raw_input to read the command lines, and readline when it is available, that's merely an example.)

A much better solution would be to actually know what kind of arguments you're expected to get and parse them as such, preferably by using a module like argparse.

Upvotes: 2

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29717

It is common handling of args, performed by shell. " and ' are ignored, since you may use them to pass, for instance, few words as one argument.

This means that you can't differentiate '1' and 1 in Python.

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375504

As you can see from your experiment, the quotes are gone by the time Python is invoked. You'll have to change how the Python is invoked.

Upvotes: 1

ajwood
ajwood

Reputation: 19027

The quotes are consumed by the shell. If you want to get them into python, you'll have to invoke like python test.py 1 "'2'" "'3'" 4

Upvotes: 4

Related Questions