【问题标题】:Calling a python script from shell but passing the location of config file as a parameter从 shell 调用 python 脚本,但将配置文件的位置作为参数传递
【发布时间】:2018-12-20 22:44:06
【问题描述】:

如何从 python 脚本(Ubuntu shell)调用函数,同时传递配置参数?相关的 SO post 似乎没有解决这个问题。

这是我现在拥有的:

$ python -c ' from python_library import * ; function() ; -config /path/to/config/file '

上述失败。以下(以及许多其他)组合也是如此:

    $ python -c ' from python_library import * ; function() -config /path/to/config/file '

    $ python -c ' from python_library import * ; function() ; -config "/path/to/config/file" '

谢谢!

【问题讨论】:

  • ` -config "/path/to/config/file"` 不是python代码,为什么要在引用的命令中包含它
  • 我正在尝试将参数(配置文件)传递给我的脚本,而原始帖子中包含的示例是失败的尝试。

标签: python shell


【解决方案1】:

您需要将 conf arg 作为 python 的另一个参数提取出来

$ python -c ' from python_library import * ; function()' -config /path/to/config/file

【讨论】:

  • 它成功了(没有单独的'-',它包含在您的原始帖子中),谢谢!
  • 如果您想在末尾添加 & 以便您的命令在后台运行并释放您的 shell 提示符以发出另一个命令?
【解决方案2】:

您可以为此使用环境变量:

MYPARAMETERS="-config /path/to/config/file" python -c "import os,sys;sys.argv = os.environ['MYPARAMETERS'].split(); import python_library import * ; function()"

【讨论】:

  • 谢谢安德烈!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2016-03-20
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多