Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 373
Steve Brown Avatar asked Dec 17 '11 05:12

Steve Brown


People also ask

How do you print multiple statements in Python?

To print multiple variables in Python, use the print() function. The print(*objects) is a built-in Python function that takes the *objects as multiple arguments to print each argument separated by a space.

Can you pass arguments to Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

How do you print the results in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


1 Answers

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']
like image 198
Filip Roséen - refp Avatar answered Sep 21 '22 13:09

Filip Roséen - refp