Python直接从命令行读参数

来源:互联网 发布:json压缩工具 编辑:程序博客网 时间:2024/06/05 16:46

由来

由于缺乏某python程序直接外部的API调用的支持,于是打算直接使用该python工具内部的api,通过几步设置好环境以后,该API可以调用并且成功。但是,发现调用应用的目标是错误的,在服务器端调用该api不能达到处理的目的,这个api应该在目标板端执行,也就是通过板子命令行执行。

解决之道

1. 板子缺乏相应的python支持,但好在是Ubuntu的系统,安装该python工具需要的包后,将该工具包源码下载,并安装到板子系统中,取得了这个包的API支持。

2. Python的-c参数可以直接在命令行中执行一个python命令

$ python -c 'import foo; print foo.hello()' 
3. 注意服务器送入板子端的指令应该是raw指令,即不会自动进行变量代换比如"必须写为\"

        cmd = ("python -c 'import linaro_image_tools.media_create.boards"
                " as lmc_boards; board_type = \"%s\"; rootfs_uuid = \"\";"
                " boot_partition = \"/dev/disk/by-label/testboot\";"
                " boot_disk = \"/mnt/boot\"; chroot_dir = \"/mnt/root\";"
                " boot_device_or_file = \"/dev/null\"; is_live = False;"
                " is_lowmem = False; consoles = \"\";"
                " board = lmc_boards.board_configs[board_type]();"
                " board.set_metadata([\"/mnt/root/tmp/%s\"]);"
                " board.populate_boot(chroot_dir, rootfs_uuid, boot_partition, "
                "boot_disk, boot_device_or_file, is_live, is_lowmem, consoles)'"
                % (board_type, hwpack_name))

参考文档

http://stackoverflow.com/questions/3987041/python-run-function-from-the-command-line

问题由来代码

延伸阅读

Simple calls to Python functions from command line or shortcut (Python recipe)(转载)

该插件要求在每一个module下都加上一段语句,该module中的函数才能被调用,见Usage

[python] view plaincopyprint?
  1. """ 
  2. PythonCall.py 
  3.  
  4. PythonCall is a shortcut that allows a CLI command with arguments to call  
  5. any function within a Python module with only two lines of plumbing code. 
  6.  
  7. Usage 
  8. ===== 
  9. * Add code below to bottom of Python module. 
  10.     if __name__ == "__main__": 
  11.         import sys, PythonCall 
  12.         PythonCall.PythonCall(sys.argv).execute() 
  13.          
  14. * From command line or desktop shortcut, build a command of form: 
  15.     <pythonpath> <module> <function> <arg1 arg2 ...> 
  16.     Example: C:\Python25\python.exe C:\Dev\PyUtils\src\TextUtils.py xclip wrap 64 
  17.              
  18. Notes 
  19. ===== 
  20. * Called functions must expect args to be strings and do their own conversions. 
  21. * No argument checking or error-checking. 
  22. * In case of exception, PythonCall sends message to stderr. 
  23. * I often use this with text I pass in via the clipboard, which requires 
  24.   code to read and write the clipboard (not included here). 
  25.  
  26. Tested with Windows; should work on other platforms. 
  27.  
  28. Jack Trainor 2008 
  29. """  
  30. import os, os.path  
  31. import sys  
  32. import types  
  33.   
  34. class PythonCall(object):  
  35.     def __init__(self, sysArgs):  
  36.         try:  
  37.             self.function = None  
  38.             self.args = []  
  39.             self.modulePath = sysArgs[0]  
  40.             self.moduleDir, tail = os.path.split(self.modulePath)  
  41.             self.moduleName, ext = os.path.splitext(tail)  
  42.             __import__(self.moduleName)  
  43.             self.module = sys.modules[self.moduleName]  
  44.             if len(sysArgs) > 1:  
  45.                 self.functionName = sysArgs[1]  
  46.                 self.function = self.module.__dict__[self.functionName]  
  47.                 self.args = sysArgs[2:]   
  48.         except Exception, e:  
  49.             sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e))  
  50.   
  51.     def execute(self):  
  52.         try:  
  53.             if self.function:  
  54.                 self.function(*self.args)  
  55.         except Exception, e:  
  56.             sys.stderr.write("%s %s\n" % ("PythonCall#execute", e))  
  57.               
  58.               
  59. #####################################################  
  60. # Test Examples - REMOVE  
  61. #  
  62. # Normally the function calls are in a module other than PythonCall.   
  63. # These are only examples.  
  64. #  
  65. # Example 1: C:\Python25\python.exe C:\Dev\PyUtils\src\PythonCall.py double 14  
  66. # Example 2: C:\Python25\python.exe C:\Dev\PyUtils\src\PythonCall.py capitalize "Four score and seven years ago..."  
  67. #####################################################  
  68.   
  69. def double(x):  
  70.     x = int(x)  
  71.     print 2 * x  
  72.   
  73. def capitalize(s):  
  74.     print s.upper()  
  75.   
  76. if __name__ == "__main__":  
  77.     import sys, PythonCall  
  78.     PythonCall.PythonCall(sys.argv).execute()  
  79.   
  80. #####################################################  
  81. # End - REMOVE  
  82. #####################################################  
原创粉丝点击