使用命令行功能从Linux执行python脚本 [英] execute python script with function from command line, Linux

查看:90
本文介绍了使用命令行功能从Linux执行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

现在我的问题是,我需要从linux命令行执行此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 user$: python convertImage.py convertFile(fileName)

这应该执行传递适当功能的python脚本.

This should execute the python script passing the appropriate function.

示例:

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命令行正确将文件名传递给函数的正确方法是什么?

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

非常感谢

推荐答案

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

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

This will work. But it's insanely dangerous.

您确实需要考虑一下命令行语法.而且,您需要考虑为什么要打破长期以来为指定程序参数指定的Linux标准.

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.

例如,您应该考虑删除示例中无用的().代替它.

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

python convertImage.py convertFile fileName

然后,您只需做很少的工作即可使用 argparse 获取命令("convertFile")和参数("fileName"),并在标准Linux命令行语法内工作.

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

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 )

这篇关于使用命令行功能从Linux执行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆