1

Is it possible to pass variables to Python when invoking a script from a bash shell?

For example, when I would call my_script in the shell like this:

python my_script.py -par1 -par2

is it possible to use par1 and par2 as variables in Python so I can pass them as arguments to a function?

Something similar like for shell scripting, where in something like this:

my_script.sh par1

par1 would be stored as $1

4

2 回答 2

2

You can get the commandline arguments from sys.argv

Python also comes with a variety of commandline processing utilities. I would recommend argparse which is included in the standard library starting with version 2.7. But there is also optparse or even getopt for the adventurous.

于 2013-03-25T19:13:23.740 回答
0

壳:

python my_script.py -par1 -par2

Python:将它们作为参数传递给函数:

import sys

arg1,arg2 = sys.argv[1:3]

myfunc(arg1,arg2)
于 2013-03-25T19:25:46.290 回答