Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute python script with function from command line, Linux

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)

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.

example:

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

This should execute the python script passing the appropriate function.

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?

Thank in advanced

like image 251
knittledan Avatar asked Oct 07 '11 18:10

knittledan


1 Answers

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.

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

python convertImage.py convertFile fileName

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 )
like image 200
S.Lott Avatar answered Sep 20 '22 00:09

S.Lott