【问题标题】:execute python script with function from command line, Linux从命令行执行带有函数的python脚本,Linux
【发布时间】:2023-06-17 08:37:02
【问题描述】:

我有一个名为 convertImage.py 的 python 文件,在文件中我有一个脚本,可以根据自己的喜好转换图像,整个转换脚本设置在一个名为 convertFile(fileName) 的函数中

现在我的问题是我需要从 linux 命令行执行这个 python 脚本,同时传递 convertFile(fileName) 函数。

示例:

 linux user$: python convertImage.py convertFile(fileName)

这应该执行传递适当函数的python脚本。

示例:

def convertFile(fileName):

    import os, sys
    import Image
    import string

    splitName = string.split(fileName, "_")
    endName = splitName[2]
    splitTwo = string.split(endName, ".")
    userFolder = splitTwo[0]

    imageFile = "/var/www/uploads/tmp/"+fileName

    ...rest of the script...

    return

执行这个python脚本并从liunx命令行正确地将文件名传递给函数的正确方法是什么?

提前致谢

【问题讨论】:

  • 没有这样的东西。解析sys.argv 列表并选择正确的操作。检查argparse模块
  • S.Lott 提到,<program> <subcommand> <command arguments> 是一种很常见的风格。用户最好有命令名称,而不是了解内部实现。并且使用括号(需要在 bash 中转义)作为语法的必需部分只是卑鄙的。
  • 括号仅作为示例,但我感谢所有帮助并使用 sys.argv 使其工作
  • @knittledan: sys.argv 通常是一个糟糕的选择。请注意,所有答案都特别建议避免这种情况。

标签: python linux shell command-line


【解决方案1】:

这个

if __name__ == "__main__":
    command= " ".join( sys.argv[1:] )
    eval( command )

这会奏效。但这非常危险。

您确实需要考虑您的命令行语法是什么。而且您需要考虑为什么要打破长期确立的用于为程序指定参数的 Linux 标准。

例如,您应该考虑删除示例中无用的()。改成这个吧。

python convertImage.py convertFile fileName

然后,您只需少量工作即可使用argparse 获取命令(“convertFile”)和参数(“fileName”),并在标准 Linux 命令行语法中工作。

function_map = { 
    'convertFile': convertFile,
    'conv': convertFile,
}
parser = argparse.ArgumentParser()
parser.add_argument( 'command', nargs=1 )
parser.add_argument( 'fileName', nargs='+' )
args= parser.parse_args()
function = function_map[args.command]
function( args.fileName )

【讨论】:

  • 通过主要解决 Y 来简要回答 X 的良好组合
  • @S.Lott function_map 字典的目的是什么?为什么它有两个命令键?
【解决方案2】:

快速而肮脏的方式:

linux user$: python convertImage.py convertFile fileName

然后在 convertImage.py 中

if __name__ == '__main__':
    import sys
    function = getattr(sys.modules[__name__], sys.argv[1])
    filename = sys.argv[2]
    function(filename)

更复杂的方法是使用 argparse(适用于 2.7 或 3.2+)或 optparse

【讨论】:

    【解决方案3】:

    创建脚本的*可执行部分,用于解析命令行参数,然后在调用中将其传递给您的函数,如下所示:

    import os, sys
    #import Image
    import string
    
    
    def convertFile(fileName):
        splitName = string.split(fileName, "_")
        endName = splitName[2]
        splitTwo = string.split(endName, ".")
        userFolder = splitTwo[0]
    
        imageFile = "/var/www/uploads/tmp/"+fileName
    
        print imageFile     # (rest of the script)
    
        return
    
    
    if __name__ == '__main__':
        filename = sys.argv[1]
        convertFile(filename)
    

    然后,从一个外壳,

    $ convertImage.py the_image_file.png
    /var/www/uploads/tmp/the_image_file.png
    

    【讨论】:

    • 这需要hashbang吗?