如何通过shell脚本为不同(Python)脚本指定默认命令行参数?

如何通过shell脚本为不同(Python)脚本指定默认命令行参数?,shell,command-line,environment-variables,command-line-arguments,Shell,Command Line,Environment Variables,Command Line Arguments,我对shell的理解非常有限,我正在做一个小任务,需要一些帮助 我得到了一个可以解析命令行参数的python脚本。其中一个参数称为“-targetdir”。如果未指定-targetdir,则默认为用户计算机上的/tmp/{USER}文件夹。我需要将-targetdir定向到特定的文件路径 实际上,我想在我的脚本中执行以下操作: 设置${-targetdir,“文件路径”} 这样python脚本就不会设置默认值。有人知道怎么做吗?我也不确定我是否提供了足够的信息,因此请让我知道我是否模棱两可。我强

我对shell的理解非常有限,我正在做一个小任务,需要一些帮助

我得到了一个可以解析命令行参数的python脚本。其中一个参数称为“-targetdir”。如果未指定-targetdir,则默认为用户计算机上的/tmp/{USER}文件夹。我需要将-targetdir定向到特定的文件路径

实际上,我想在我的脚本中执行以下操作:

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

这样python脚本就不会设置默认值。有人知道怎么做吗?我也不确定我是否提供了足够的信息,因此请让我知道我是否模棱两可。

我强烈建议修改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
}
#!/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
如果放入用户的
.bashrc
,则从用户的交互式shell调用
foobar
(假设他们正在使用bash)将替换为上述包装。请注意,这不会影响其他壳
export-f foobar
将导致bash的其他实例使用包装器,但这不能保证扩展到
sh
的实例,如
system()
调用、Python的
Popen(…,shell=True)
和系统中的其他地方所使用的


选项B:外壳包装器 假设您将原始的
foobar
脚本重命名为
foobar.real
。然后您可以制作
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
}
#!/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
,而不保留内存。

不清楚
set
语法的实际作用(它不会更改bash中常规shell变量的值)。如果您想将脚本中的一个参数解析为一个变量,那么我们有一些现有的Q&a条目,其中包括……的最佳实践,有关一些示例,请参阅;这里的第一个大代码块接受
--files
来设置变量
file
-v
来更改变量
verbose
,等等……也就是说,我想知道如果还没有一个给定的参数,您是否想用shell函数或添加
-targetdir
参数的脚本来包装Python脚本?这是可行的,如果不搜索它是否已经在知识库中,我不知道。顺便说一句,如果您的Python程序确实从环境中获取了一个
targetdir
(正如问题上的标记所暗示的),而不是在没有显式标志的情况下返回到
/tmp
,这个问题将是没有意义的:您可以只导出targetdir=filepath,然后依靠Python代码查找
os.environ['targetdir']