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']
Answer from Filip Roséen on Stack OverflowYou'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']
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:]))
Getting all arguments from a function call in python
python - How do I access command line arguments? - Stack Overflow
How to get complete list of arguments for function from module in python - Stack Overflow
python - How can I read and process (parse) command line arguments? - Stack Overflow
Essentially, I'm trying to work out how to, from within a function, get a completely populated *args and **kwargs, including the function's named parameters.
How about saving the arguments via locals() at the beginning of the function?
def my_func(a, *args, **kwargs):
saved_args = {**locals()} # Updated to make a copy per loco.loop
print("saved_args is", saved_args)
local_var = 10
print("saved_args is", saved_args)
print("But locals() is now", locals())
my_func(20, 30, 40, 50, kwarg1='spam', kwarg2='eggs')
It gives this output:
saved_args is {'a': 20, 'args': (30, 40, 50), 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}
saved_args is {'a': 20, 'args': (30, 40, 50), 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}
But locals is now {'a': 20, 'saved_args': {...}, 'args': (30, 40, 50), 'local_var': 10, 'kwargs': {'kwarg1': u'spam', 'kwarg2': u'eggs'}}
Hat tip: https://stackoverflow.com/a/3137022/2829764
Not something I'd do, but you could use inspect.signature to introspect the arguments your method takes:
>>> import inspect
>>> def foobar(foo, bar, baz):
... return inspect.signature(foobar)
...
>>> foobar(1, 2, 3)
<Signature (foo, bar, baz)>
The returned Signature instance has an ordered collection of parameters (the .parameters attribute) which can then be used together with locals() to produce a list of your argument values:
>>> def foobar(foo, bar, baz):
... sig, foobar_locals = inspect.signature(foobar), locals()
... return [foobar_locals[param.name] for param in sig.parameters.values()]
...
>>> foobar(1, 2, 3)
[1, 2, 3]
However, you really only need such magic when doing advanced function decorators and the like. I think it's overkill here.
Hello,
Im trying to find out if there is a way to access all arguments passed to a function (perhaps in a dictionary) from within a function? Does anyone know a way to do this?
For example if I have
def myfunc(a,b,c,d):
passIs there some line of code I can use that will let me gather all the arguments passed into a list or a dictionary?
Thanks
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
I highly recommend argparse which comes with Python 2.7 and later.
The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1 As one would expect:
2
There is no way to do this generically, help(<function>) will at a minimum return you the function signature (including the argument names), Python is dynamically typed so you don't get any types and arguments by themselves don't tell you what the valid values are. This is where a good docstring comes in.
However, the csv module does have a specific function for listing the dialects:
>>> csv.list_dialects()
['excel', 'excel-tab', 'unix']
>>> help(csv.excel)
Help on class excel in module csv:
class excel(Dialect)
| Describe the usual properties of Excel-generated CSV files.
...
The inspect module is extremely powerful. To get a list of classes, for example in the csv module, you could go:
import inspect, csv
from pprint import pprint
module = csv
mod_string = 'csv'
module_classes = inspect.getmembers(module, inspect.isclass)
for i in range(len(module_classes)):
myclass = module_classes[i][0]
myclass = mod_string+'.'+myclass
myclass = eval(myclass)
# could construct whatever query you want about this class here...
# you'll need to play with this line to get what you want; it will failasis
#line = inspect.formatargspect(*inspect.getfullargspec(myclass))
pprint(myclass)
Hope this helps get you started!
import sys
print("\n".join(sys.argv))
sys.argv is a list that contains all the arguments passed to the script on the command line. sys.argv[0] is the script name.
Basically,
import sys
print(sys.argv[1:])
The canonical solution in the standard library is argparse (docs):
Here is an example:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
argparse supports (among other things):
- Multiple options in any order.
- Short and long options.
- Default values.
- Generation of a usage help message.