从命令行,Linux 使用函数执行 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7691599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:32:28  来源:igfitidea点击:

execute python script with function from command line, Linux

pythonlinuxshellcommand-line

提问by knittledan

I have my python file called convertImage.py and inside the file I have a script that converts an image to my liking, the entire converting script is set inside a function called convertFile(fileName)

我有一个名为 convertImage.py 的 python 文件,在文件中我有一个将图像转换为我喜欢的脚本,整个转换脚本设置在一个名为 convertFile(fileName) 的函数中

Now my problem is I need to execute this python script from the linux command line while passing the convertFile(fileName) function along with it.

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

example:

例子:

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

This should execute the python script passing the appropriate function.

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

example:

例子:

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

What is the right way to execute this python script and properly pass the file name to the function from the liunx command line?

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

Thank in advanced

提前致谢

采纳答案by S.Lott

This

这个

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

This will work. But it's insanely dangerous.

这将起作用。但这是非常危险的。

You really need to think about what your command-line syntax is. And you need to think about why you're breaking the long-established Linux standards for specifying arguments to a program.

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

For example, you should consider removing the useless ()'s in your example. Make it this, instead.

例如,您应该考虑删除示例中的无用()'s。改为这样。

python convertImage.py convertFile fileName

Then, you can -- with little work -- use argparseto get the command ("convertFile") and the arguments ("fileName") and work within the standard Linux command line syntax.

然后,您可以 - 只需很少的工作 - 用于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 )

回答by Ethan Furman

Quick and dirty way:

快速而肮脏的方式:

linux user$: python convertImage.py convertFile fileName

and then in convertImage.py

然后在 convertImage.py

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

A more sophisticated approach would use argparse(for 2.7 or 3.2+) or optparse.

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

回答by Santa

Create a top-level executable part of your script that parses command-line argument(s) and then pass it to your function in a call, like so:

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

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)

Then, from a shell,

然后,从一个壳,

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