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,510 points
889 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,880 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
2 answers

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

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 580 points
1,465 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,149 views
0 votes
0 answers

How do I access environment variables in Python?

May 26, 2022 in Python by Kichu
• 19,050 points
549 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
964 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,060 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,880 points
678 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,880 points
696 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