【问题标题】:Calling python function from shell script [duplicate]从shell脚本调用python函数[重复]
【发布时间】:2016-03-13 23:22:40
【问题描述】:

谁能帮助我了解语法,如何从 shell 脚本调用“x”函数。这里的挑战是,shell 脚本需要动态传递 a、b。

非常感谢您的建议。

Python 代码:

def x(a,b):
    '''x(a,b) --> [a,b]'''
    return [a,b]

def add(a,b):
    '''add(a,b) --> a+b'''
    return a+b

def test():
    '''test code for all modules'''
    print "testing x..."
    print x(1,2)
    print x('a','b')
    print x([1,2,3],[4,5,6])
    print "testing add..."
    print add(1,2)
    print add('a','b')
    print add([1,2,3],[4,5,6])
    return

【问题讨论】:

  • 哇。发帖前的终极搜索失败。
  • @MadPhysicist,但这个答案是旧的,不符合 Python3
  • @JohnLaRooy 这不是 Python3 问题,*nix 上的 $ python 应该始终运行 python2。如果您想更新答案,请在副本上执行此操作。
  • @AdamSmith,Arch linux 已经默认使用 python3,而 Ubuntu 16.04 正计划从 python2 中移除……,PEP0394 说“暂时……”
  • @JohnLaRooy 是这样吗?惊人的!就我而言,Python2 一直是一具腐烂的尸体。

标签: python shell


【解决方案1】:

如果你保存文件foo.py,你可以从shell运行它

python -c "import foo; print(foo.x(1, 2))"

结果可以从标准输出中读取。

【讨论】:

  • 感谢您的回复。但我需要动态传递参数。像 python -c "import foo; print(foo.x(${var1}, ${var2}))"
  • 那就这样吧。是什么阻止了你?
  • 这不适用于我们的 Red Hat Enterprise Linux Server 5.11 版,请帮我确定替代方案
猜你喜欢
  • 2019-10-31
  • 2012-01-23
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多