小编Sha*_*odi的帖子

使用argparse解析形式为"arg = val"的参数

我想使用argparse来解析形式为"arg = val"的命令行.例如,用法是:

script.py conf_dir=/tmp/good_conf
Run Code Online (Sandbox Code Playgroud)

要实现它,我这样做:

desc   = "details"
parser = argparse.ArgumentParser(description=desc, add_help=False)
args = parser.add_argument("conf_dir")
args = parser.parse_args("conf_dir=FOO".split())
args = parser.parse_args()
print args.conf_dir
Run Code Online (Sandbox Code Playgroud)

但是,问题在于,在调用脚本时:

python script.py conf_dir=/tmp/good_conf
Run Code Online (Sandbox Code Playgroud)

我明白了:

conf_dir=/tmp/good_conf
Run Code Online (Sandbox Code Playgroud)

我期待的地方

/tmp/good_conf
Run Code Online (Sandbox Code Playgroud)

所以,问题是:我可以使用argparse来解析包含名称值对的cmd行吗?任何提示?

编辑:我想这样做的原因而不是像--conf_dir =/tmp/good_dir这样的东西是因为还有其他工具(用其他语言编写),它使用conf_dir =/tmp/good_dir样式的参数.为了保持一致性,我是以这种方式解析args.

python command-line parsing argparse

19
推荐指数
2
解决办法
9184
查看次数

将参数传递给 subprocess.Popen() 调用的“可执行”参数

subprocess.Popen() 允许您通过“可执行”参数传递您选择的 shell。
我选择传递“/bin/tcsh”,并且我不希望 tcsh 读取我的~/.cshrc.
tcsh 手册说我需要传递-fto/bin/tcsh才能做到这一点。

如何让 Popen 使用 -f 选项执行 /bin/tcsh?

import subprocess

cmd = ["echo hi"]
print cmd

proc = subprocess.Popen(cmd, shell=False,  executable="/bin/tcsh", stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()

for line in proc.stdout:
    print("stdout: " + line.rstrip())

for line in proc.stderr:
    print("stderr: " + line.rstrip())

print return_code
Run Code Online (Sandbox Code Playgroud)

python subprocess tcsh

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

argparse ×1

command-line ×1

parsing ×1

subprocess ×1

tcsh ×1