Don't reinvent the wheel. Use the argparse module, be explicit and pass in actual lists of parameters
import argparse
# defined command line options
# this also generates --help and error handling
CLI=argparse.ArgumentParser()
CLI.add_argument(
"--lista", # name on the CLI - drop the `--` for positional/required parameters
nargs="*", # 0 or more values expected => creates a list
type=int,
default=[1, 2, 3], # default if nothing is provided
)
CLI.add_argument(
"--listb",
nargs="*",
type=float, # any type/callable can be used here
default=[],
)
# parse the command line
args = CLI.parse_args()
# access CLI options
print("lista: %r" % args.lista)
print("listb: %r" % args.listb)
You can then call it using
$ python my_app.py --listb 5 6 7 8 --lista 1 2 3 4
lista: [1, 2, 3, 4]
listb: [5.0, 6.0, 7.0, 8.0]
Answer from user5349916 on Stack OverflowDon't reinvent the wheel. Use the argparse module, be explicit and pass in actual lists of parameters
import argparse
# defined command line options
# this also generates --help and error handling
CLI=argparse.ArgumentParser()
CLI.add_argument(
"--lista", # name on the CLI - drop the `--` for positional/required parameters
nargs="*", # 0 or more values expected => creates a list
type=int,
default=[1, 2, 3], # default if nothing is provided
)
CLI.add_argument(
"--listb",
nargs="*",
type=float, # any type/callable can be used here
default=[],
)
# parse the command line
args = CLI.parse_args()
# access CLI options
print("lista: %r" % args.lista)
print("listb: %r" % args.listb)
You can then call it using
$ python my_app.py --listb 5 6 7 8 --lista 1 2 3 4
lista: [1, 2, 3, 4]
listb: [5.0, 6.0, 7.0, 8.0]
Command line arguments are always passed as strings. You will need to parse them into your required data type yourself.
>>> input = "[2,3,4,5]"
>>> map(float, input.strip('[]').split(','))
[2.0, 3.0, 4.0, 5.0]
>>> A = map(float, input.strip('[]').split(','))
>>> print(A, type(A))
([2.0, 3.0, 4.0, 5.0], <type 'list'>)
There are libraries like argparse and click that let you define your own argument type conversion but argparse treats "[2,3,4]" the same as [ 2 , 3 , 4 ] so I doubt it will be useful.
edit Jan 2019 This answer seems to get a bit of action still so I'll add another option taken directly from the argparse docs.
You can use action=append to allow repeated arguments to be collected into a single list.
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
In this case you would pass --foo ? once for each list item. Using OPs example: python filename.py --foo 2 --foo 3 --foo 4 --foo 5 would result in foo=[2,3,4,5]
Tasks = []
def show_menu():
print("""
===== TO-DO LIST MENU =====
1. Add Task
2. View Tasks
3. Mark Task as Complete
4. Delete Task
5. Exit
""")
def add_task():
task_description = input("Enter task Description: ")
Tasks.append(task_description)
def view_tasks():
for index, item in enumerate(Tasks):
print(f"{index} -> {item}")
def mark_task_complete():
choice = int(input("Which task number do you want to mark as complete: "))
index = choice-1
Tasks[index] ='\u2713'
def delete_task():
choice = int(input("Which Tasks Do you want to delete?: "))
index = choice -1
if index >= 0 and index < len(Tasks):
Tasks.pop(index)
print("Task deleted successfully.")
else:
print("Invalid task number.")
while True:
show_menu()
choice = input("Enter your choice: ")
if choice == "1":
add_task()
elif choice == "2":
view_tasks()
elif choice == "3":
mark_task_complete()
elif choice == "4":
delete_task()
elif choice == "5":
print("Good bye")
break
else:
print("Invalid choice, Please try again")
what should i add or how should make it advanced or is it enough for a begginer,
i am just a begginer who just learned functions and lists and tried this one project
There are two options that I can think of:
- Use optparse, and use
appendaction to specify what you want to do as:foo.py --my_list=1 --my_list=2 .... - Specify your commandline as
foo.py --my_list='1,2,3,4,5', and then usex.split(',')to get your values in a list. You can usegetoptoroptparsefor this method.
The advantage of the first method is that you can get integer values in the list directly, at the expense of the commandline being longer (but you can add a single-charecter option for --my_list if you want). The advantage of the second is shorter command line, but after the split(), you need to convert the string values '1', '2', etc., to integers (pretty easy as well).
If I can't use a standard parser (optparse or argparse) to my application then I use the ast.literal_eval function to parse input arguments of type list as follows:
import sys, ast
inputList = ast.literal_eval( sys.argv[1] )
print type( inputList )
print inputList
Let suppose that this code is stored in testParser.py file. By executing the script:
$ python testParser.py "[1,2,3,4, [123, 456, 789], 'asdasd']"
we get the following output:
<type 'list'>
[1, 2, 3, 4, [123, 456, 789], 'asdasd']
So, using the secure enough ast.literal_eval function and inserting the list as a string of code we have the desirable result.
Useful links:
Using python's eval() vs. ast.literal_eval()?
http://docs.python.org/2/library/functions.html?highlight=eval#eval