python sys.argv differentiate int and string

11,861

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

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.

Share:
11,861
Tyler Liu
Author by

Tyler Liu

My name is Tyler Liu and I am currently living near San Francisco bay area. I've created and participated lots of open source projects: https://github.com/tylerlong Here is my technical blog: https://medium.com/@tylerlong I call myself the super full stack engineer. I can program in JavaScript, C#, Java, Python, Ruby and Swift, each with more than 3 years hands-on experience. I can learn any new programming language in a week and be proficient in it in a month. My favorite language is JavaScript, because of Atwood's Law: "Any application that can be written in JavaScript, will eventually be written in JavaScript."

Updated on June 04, 2022

Comments

  • Tyler Liu
    Tyler Liu almost 2 years

    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.