dopatraman
dopatraman

Reputation: 13908

what is a commandline argument?

I am a newcomer to python (also very sorry if this is a newb question but) i have no idea what a command line argument is. when sys.argv is called, what exactly are the arguments? Any help with understanding this would be a great service.

Upvotes: 2

Views: 271

Answers (5)

checker
checker

Reputation: 531

The arguments are usually used as a way of telling the program what it should do when it is run.

If I had a program named writefile.py, and I wanted the user to tell it which file to write, then I would run it with python writefile.py targetfile.txt. My sample writefile.py:

import sys

file = open(sys.argv[1], 'w') # sys.argv[0] = 'writefile.py' (unutbu's answer)
file.write('ABCDE')
file.close

After running this, I'll have a file named targetfile.txt with the contents "ABCDE". If I ran it with python writefile.py abcde.txt, I'd have abcde.txt with the contents "ABCDE".

Upvotes: 0

unutbu
unutbu

Reputation: 879591

Try running this program:

import sys
print(sys.argv)

You should see results similar to this:

% test.py
['/home/unutbu/pybin/test.py']
% test.py foo
['/home/unutbu/pybin/test.py', 'foo']
% test.py foo bar
['/home/unutbu/pybin/test.py', 'foo', 'bar']
% python test.py foo
['test.py', 'foo']

So, you see sys.argv is a list. The first item is the path to (or filename of) the script being run, followed by command-line arguments.

Upvotes: 7

Óscar López
Óscar López

Reputation: 236004

The command line arguments are the strings you type after a command in the command line, for instance:

python --help

Here --help is the argument for the python command, that shows a help page with the valid command line arguments for the python command.

In a python program, you have access to the arguments in sys.argv, so let's say you started a python script like this:

python myscript.py -x -y

When myscript.py starts, sys.argv[1] will have as value the string '-x' and sys.argv[2] will have as value the string '-y'. What you do with those arguments is up to you, and there are modules to help you easily define command line arguments, for instance argparse.

Upvotes: 0

Espen Burud
Espen Burud

Reputation: 1881

Command line arguments are parameters you type after the script name. Eg. if you type: python test.py arg1, the first argument is arg1.

For examples, take a look at jhu.edu.

Upvotes: 0

gpojd
gpojd

Reputation: 23065

Given the command myscript.py arg1 arg2 arg3, the arguments are arg1, arg2 and arg3. sys.argv will also include the script name (i.e. myscript.py) in the first position.

Command line arguments are not specific to python.

Upvotes: 6

Related Questions