开发者

run a function (from a .py file) from a linux console

开发者 https://www.devze.com 2023-01-26 08:00 出处:网络
maybe the title is not very clear, let me elaborate. I have a python script that open a ppm file , apply a chosen filter(rotations...) and create a new picture. until here everything work fine.

maybe the title is not very clear, let me elaborate.

I have a python script that open a ppm file , apply a chosen filter(rotations...) and create a new picture. until here everything work fine.

but I want to do the same thing through a l开发者_开发问答inux console like:

ppmfilter.py ROTD /path/imageIn.ppm /path/imageOut.ppm

here ROTD is the name of the function that apply a rotation.

I don't know how to do this, I'm looking for a library that'll allow me to do this.

looking forward for your help.

P.S.: I'm using python 2.7


There is a relatively easy way:

You can determine the global names (functions, variables, etc.) with the use of 'globals()'. This gives you a dictionary of all global symbols. You'll just need to check the type (with type() and the module types) and if it's a function, you can call it with sys.argv:

import types
import sys

def ROTD(infile, outfile):
    # do something

if __name__ == '__main__':
    symbol = globals().get(sys.argv[1])
    if hasattr(symbol, '__call__'):
        symbol(*sys.argv[2:])

This will pass the program argument (excluding the filename and the command name) to the function.

EDIT: Please, don't forget the error handling. I omited it for reasons of clarity.


Use main() function:

def main()
   # call your function here

if __name__ == "__main__":
   main()


A nice way to do it would be to define a big dictionary {alias: function} inside your module. For instance:

actions = {
    'ROTD': ROTD,
    'REFL': reflect_image,
    'INVT': invIm,
}

You get the idea. Then take the first command-line argument and interpret it as a key of this dictionary, applying actions[k] to the rest of the arguments.


You can define in your ppmfilter.py main section doing this:

if __name__ == "__main__":
  import sys
  ROTD(sys.argv[1], sys.argv[2]) # change according to the signature of the function

and call it: python ppmfilter.py file1 file2

You can also run python -c in the directory that contains you *.py file:

python -c "import ppmfilter; ppmfilter.ROTD('/path/to/file1', '/path/to/file2')"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号