25

How can I print all arguments passed to a python script?

This is what I was trying:

#!/usr/bin/python
print(sys.argv[1:]);

update

How can I save them to a file?

#!/usr/bin/python
import sys
print sys.argv[1:]
file = open("/tmp/test.txt", "w")
file.write(sys.argv[1:])

I get

TypeError: expected a character buffer object
Steve Brown
  • 1,336
  • 4
  • 16
  • 20
  • 3
    Instead of saying "this does not work", take time to find out *why* it "doesn't work". This includes things like reading -- *and posting* -- the error messages/symptoms. –  Dec 17 '11 at 05:34

3 Answers3

50

You'll need to import sys for that to work.

#!/usr/bin/python

import sys
print  sys.argv[1:]

Example

:/tmp% cat foo.py
#!/usr/bin/python

import sys
print (sys.argv[1:]);

:/tmp% python foo.py 'hello world' arg3 arg4 arg5
['hello world', 'arg3', 'arg4', 'arg5']
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
5

the problem is with the list of args that write can't handle.

You might want to use:

file.write('\n'.join(sys.argv[1:]))
davidep
  • 51
  • 1
  • 1
4

Your last line is wrong.

It should be:

file.writelines(sys.argv[1:])
jgritty
  • 11,660
  • 3
  • 38
  • 60