mch*_*hid 14 python command-line bash scripts
我有这个 python 脚本:
#!/usr/bin/env python
def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )
getPermutation('abcd','')
Run Code Online (Sandbox Code Playgroud)
但是,我希望能够使用“abcd”的变量来调用此脚本,因此我可以插入任意字母组合而不是“abcd”,例如“efgh”。
通常,我可以在 bash 脚本的最后一行使用$@或$1代替,abcd如下所示:
#!/usr/bin/env python
def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )
getPermutation("$1",'')
Run Code Online (Sandbox Code Playgroud)
但是当我使用类似的东西运行脚本时./scriptname.py efgh:
$1
1$
Run Code Online (Sandbox Code Playgroud)
而不是“efgh”的排列。
ste*_*ver 24
蟒等效shell的位置参数阵列$1,$2等等是sys.argv
所以:
#!/usr/bin/env python
import sys
def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )
getPermutation(sys.argv[1],'')
Run Code Online (Sandbox Code Playgroud)
然后
$ ./foo.py abcd
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
Run Code Online (Sandbox Code Playgroud)
参数化python的很多方法。位置参数、环境变量和命名参数。环境变量:
导入 os 并使用 getenv ,如:
fw_main_width =os.getenv('FW_MAIN_WIDTH', fw_main_width)
Run Code Online (Sandbox Code Playgroud)
其中第二个参数是未设置 env 变量的默认值。
位置参数:
导入 sys 后使用 sys.argc、sys.argv[n]。
命名参数:
或者对于命名参数,(你问的)
import argparse
Run Code Online (Sandbox Code Playgroud)
然后描述可能的参数:
parser = argparse.ArgumentParser(description = "Project", fromfile_prefix_chars='@')
parser.add_argument("-V", "--version", help="show program version", action="store_true")
parser.add_argument("-W", "--width", help="set main screen width")
read arguments from the command line
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
并将它们用作 args.width 等。
| 归档时间: |
|
| 查看次数: |
21134 次 |
| 最近记录: |