I would like to specify a file for manipulation from the command line. I am new to python so I'm not really sure how to begin this. I am guessing that I need some options?

Recommended Answers

All 4 Replies

You need what are called 'command line arguments'. Dive into python has a great section explaining command line arguments. But in essence you could do something like this:

import sys
if sys.argv:
    print "The first command line argument i recieved was:",sys.argv[0]

Then we would run our code like this:

python filename.py ThisIsTheArgument

And the result would print the following out

The first command line argument i recieved was: ThisIsTheArgument

So i'm sure you can see that instead of writing 'ThisIsTheArgument' that you could put a path to a file there instead and then do things to it in your program. Anyway, have a look at the link above, it'll help you out :)

Good answer but permit me to suggest a minor change to the above example.

#!/usr/bin/env python
#argecho.py
import sys
if sys.argv:
    print "The name of this program is:",sys.argv[0]
    print "The first command line argument I received is:",sys.argv[1]
    print "The second command line argument I received is:",sys.argv[2]
commented: Woops :) my bad. Nicely done +2

Ok, but I need to do this for an arbitrary number of file names. Is there any way to completely remove the first element in the array and make the file path the first element?

Ok, but I need to do this for an arbitrary number of file names. Is there any way to completely remove the first element in the array and make the file path the first element?

Create an empty list and append what you want from sys.argv into your list.

import sys

# there is a commandline
if len(sys.argv) > 1:
    arglist = []
    # sys.argv[0] is the program filename, slice it off
    for arg in sys.argv[1:]: #Slice of sys.argv starting at sys.argv[1] up to and including the end
        arglist.append(arg)
else:
    print "usage %s arg1 arg2 [arg3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were This.txt That.txt Other.log
# arglist should be ['This.txt', 'That.txt', 'Other.log']
print(arglist)
commented: nice +10
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.