How do I access command line arguments in Python

0 votes

I use python to create my project settings setup, but I need help getting the command line arguments.

I tried this on the terminal:

$python myfile.py var1 var2 var3

In my Python file, I want to use all variables that are input.

May 11, 2020 in Python by kartik
• 37,520 points
1,297 views

2 answers to this question.

0 votes

Hii,

You can use sys.argv to get the arguments as a list.

If you need to access individual elements you can use:

sys.argv[i]  

where i is the index 0 that will give you the python filename being executed. Any index after that are the arguments passed.

Thank You!!

answered May 11, 2020 by Niroj
• 82,840 points
0 votes
import sys
print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
answered Jun 25, 2020 by Karan

Related Questions In Python

0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,300 points
1,809 views
0 votes
1 answer

How to input optional arguments in python command line?

Please use this code. if len(sys.argv) == 2: first_log ...READ MORE

answered Jul 11, 2019 in Python by Suri
7,710 views
0 votes
0 answers

How do I access environment variables in Python?

May 26, 2022 in Python by Kichu
• 19,040 points
845 views
0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27, 2019 in Python by rajesh
• 1,270 points
1,341 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,454 views
0 votes
1 answer
0 votes
1 answer

How do I merge two dictionaries in a single expression in Python?

Hello, For dictionaries x and y, z becomes a shallowly merged dictionary with ...READ MORE

answered Apr 13, 2020 in Python by Niroj
• 82,840 points
995 views
0 votes
1 answer

how do i get anova table of split plot design or factorial experimental design in python?

Hello @ kapil, For your query you can refer ...READ MORE

answered Aug 24, 2020 in Python by Niroj
• 82,840 points
975 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP