Created
January 21, 2017 12:07
-
-
Save badbye/413b630f37b69466b485c2a5f352cbde to your computer and use it in GitHub Desktop.
Magic: extract arguments from function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # encoding: utf8 | |
| """ | |
| Created on 2017.01.21 | |
| @author: yalei | |
| """ | |
| import sys | |
| import traceback | |
| import re | |
| def test_abc(*args, **kwargs): | |
| raise Exception() | |
| def valid_exp(s): | |
| bracket = [] | |
| res = '' | |
| for i in s: | |
| s = s.lstrip(i) | |
| if i in [',', ')'] and bracket == []: | |
| return res, s | |
| if i in ['(', '[', '{']: | |
| bracket.append(i) | |
| elif i in [')', ']', '}']: | |
| bracket.pop() | |
| res += i | |
| return res, s | |
| def call_argument(): | |
| try: | |
| a = 1 | |
| b = 2 | |
| # find arguments in this function | |
| test_abc(a + 1 + 1, b - 2 / 4) | |
| except: | |
| error = sys.exc_info() | |
| error = '\n'.join(traceback.format_exception(*error)) | |
| arg_strings = re.search('test_abc\((.*)', error).groups()[0] | |
| args = [] | |
| while arg_strings: | |
| arg, arg_strings = valid_exp(arg_strings) | |
| args.append(arg.strip()) | |
| return args | |
| if __name__ == '__main__': | |
| args = call_argument() | |
| for i,arg in enumerate(args): | |
| print 'The %sth argument: [%s]' % (i+1, arg) | |
| """ | |
| Run in Python shell: | |
| ``` | |
| from test_arg import * | |
| args = call_argument() | |
| print args | |
| ``` | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment