0

Have a question,

I'm writing a python-script and need to pass argument to the script from cmd.

My code to implement this little feature:

import sys

cars = sys.argv[1]

From command line, I type the next command:

python my_script.py ("Opel", "Nissan", 'Reno')

But when I checked the results, it was not a tuple, it was a string. How can I get a tuple from argument?

Artsom
  • 161
  • 3
  • 11
  • @Sherzod I have already read this topic, but it doesn't help me, I need a solution for this case – Artsom Mar 31 '20 at 09:29

3 Answers3

4

The command line does not know about Python data structures. All you get from there are strings. You can create them in Python, however:

cars = sys.argv[1].split()
# cars = tuple(sys.argv[1].split())

and call script as

python my_script.py "Opel Nissan Reno"

For more advanced argument processing, you should consider using the argparse module.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

command line is not define tuple. try this from command line

python my_script.py "Opel" "Nissan" "Reno"
import sys
# get from 1 to end
cars = sys.argv[1:]
0

How about this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--data', nargs='+', type=str)
args = parser.parse_args()
my_tuple = tuple(args.data)
print(type(my_tuple)) # Check type

Run:

python my_script.py --data Opel Nissan Reno

Output:

<class 'tuple'>
Scott
  • 4,974
  • 6
  • 35
  • 62