【问题标题】:How do I specify a default command-line argument for a different (Python) script via a shell script?如何通过 shell 脚本为不同的 (Python) 脚本指定默认命令行参数?
【发布时间】:2019-01-20 16:50:23
【问题描述】:

我对 shell 的了解非常少,我正在做一个小任务,需要一些帮助。

我得到了一个可以解析命令行参数的 python 脚本。这些参数之一称为“-targetdir”。当 -targetdir 未指定时,它默认为用户机器上的 /tmp/{USER} 文件夹。我需要将 -targetdir 指向特定的文件路径。

我实际上想在我的脚本中做这样的事情:

设置 ${-targetdir, "文件路径"}

这样python脚本就不会设置默认值。有人知道该怎么做吗?我也不确定我是否提供了足够的信息,所以如果我有歧义,请告诉我。

【问题讨论】:

  • 不清楚您期望set 语法实际上执行 (它 更改bash 中常规shell 变量的值)。如果您想将脚本的参数解析为变量,我们有一些现有的问答条目以及最佳实践...
  • ...见BashFAQ #35 的一些例子;那里的第一个大代码块接受--files 设置变量file-v 更改变量verbose 等。
  • ...也就是说,我想知道您是否想要做的是 wrap 带有 shell 函数的 Python 脚本或添加 -targetdir 参数的脚本(如果有)不是已经给了吗?这是可行的,如果不搜索它是否已经在知识库中,我不知道。
  • 顺便说一句,如果您的 Python 程序 确实 从环境中获取 targetdir(正如问题上的标记所暗示的那样),而不是在缺席的情况下回退到 /tmp如果没有明确的标志,这个问题将没有实际意义:您可以只使用export targetdir=filepath,然后依靠 Python 代码来查找 os.environ['targetdir']

标签: shell command-line environment-variables command-line-arguments


【解决方案1】:

强烈建议修改 Python 脚本以明确指定所需的默认值,而不是参与这种黑客行为。

也就是说,一些方法:


选项 A:函数包装器

假设您的 Python 脚本名为 foobar,您可以编写如下包装函数:

foobar() {
  local arg found=0
  for arg; do
    [[ $arg = -targetdir ]] && { found=1; break; }
  done
  if (( found )); then
    # call the real foobar command without any changes to its argument list
    command foobar "$@"
  else
    # call the real foobar, with ''-targetdir filepath'' added to its argument list
    command foobar -targetdir "filepath" "$@"
  fi
}

如果放入用户的.bashrc,则从用户的交互式 shell(假设他们使用 bash)对 foobar 的任何调用都将替换为上述包装器。请注意,这不会影响其他 shell; export -f foobar 将导致 bash 的其他实例遵循包装器,但这不能保证扩展到 sh 的实例,正如 system() 调用、Python 的 Popen(..., shell=True) 和系统中的其他地方所使用的那样。


选项 B:外壳包装器

假设您将原始 foobar 脚本重命名为 foobar.real。然后您可以将foobar 设为包装器,如下所示:

#!/usr/bin/env bash
found=0
for arg; do
  [[ $arg = -targetdir ]] && { found=1; break; }
done
if (( found )); then
  exec foobar.real "$@"
else
  exec foobar.real -targetdir "filepath" "$@"
fi

使用exec 会终止包装器的执行,将其替换为foobar.real 而不会保留在内存中。

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2011-07-26
    • 2014-01-25
    • 2021-03-20
    • 2021-02-04
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多