print "The first command line argument i recieved was:",sys.argv
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.
print "The name of this program is:",sys.argv
print "The first command line argument I received is:",sys.argv
print "The second command line argument I received is:",sys.argv
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.
# there is a commandline
if len(sys.argv) > 1:
arglist = 
# sys.argv is the program filename, slice it off
for arg in sys.argv[1:]: #Slice of sys.argv starting at sys.argv up to and including the end
print "usage %s arg1 arg2 [arg3 ...]" % sys.argv
# if the arguments were This.txt That.txt Other.log
# arglist should be ['This.txt', 'That.txt', 'Other.log']