Pass arguments including them in the file with python

1

Hello, I'm checking a small program in python which I'm going through a series of arguments from the console. But now what I wanted to do was to be able to put these arguments from the .py. I give an example about the code:

Edited code:

# Print the title
Header().first_title()

parser = MyParser()
parser.add_argument('--version', action='version', version='Version ' + str(constant.CURRENT_VERSION), help='laZagne version')

# ------------------------------------------- Permanent options -------------------------------------------
# Version and verbosity 
PPoptional = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
PPoptional._optionals.title = 'optional arguments'
PPoptional.add_argument('-v', dest='verbose', action='count', default=0, help='increase verbosity level')
PPoptional.add_argument('-path', dest='path',  action= 'store', help = 'path of a file used for dictionary file')
PPoptional.add_argument('-b', dest='bruteforce',  action= 'store', help = 'number of character to brute force')

# Output 
PWrite = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
PWrite._optionals.title = 'Output'
PWrite.add_argument('-oN', dest='write_normal',  action='store_true', help = 'output file in a readable format')
PWrite.add_argument('-oJ', dest='write_json',  action='store_true', help = 'output file in a json format')
PWrite.add_argument('-oA', dest='write_all',  action='store_true', help = 'output file in all format')

# ------------------------------------------- Add options and suboptions to all modules -------------------------------------------
all_subparser = []
for c in category:
    category[c]['parser'] = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
    category[c]['parser']._optionals.title = category[c]['help']

    # Manage options
    category[c]['subparser'] = []
    for module in modules[c].keys():
        m = modules[c][module]
        category[c]['parser'].add_argument(m.options['command'], action=m.options['action'], dest=m.options['dest'], help=m.options['help'])

        # Manage all suboptions by modules
        if m.suboptions and m.name != 'thunderbird':
            tmp = []
            for sub in m.suboptions:
                tmp_subparser = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
                tmp_subparser._optionals.title = sub['title']
                if 'type' in sub:
                    tmp_subparser.add_argument(sub['command'], type=sub['type'], action=sub['action'], dest=sub['dest'], help=sub['help'])
                else:
                    tmp_subparser.add_argument(sub['command'], action=sub['action'], dest=sub['dest'], help=sub['help'])
                tmp.append(tmp_subparser)
                all_subparser.append(tmp_subparser)
            category[c]['subparser'] += tmp

# ------------------------------------------- Print all -------------------------------------------
parents = [PPoptional] + all_subparser + [PWrite]
dic = {'all':{'parents':parents, 'help':'Run all modules', 'func': runAllModules}}
for c in category:
    parser_tab = [PPoptional, category[c]['parser']]
    if 'subparser' in category[c]:
        if category[c]['subparser']:
            parser_tab += category[c]['subparser']
    parser_tab += [PWrite]
    dic_tmp = {c: {'parents': parser_tab, 'help':'Run %s module' % c, 'func': runModule}}
    dic = dict(dic.items() + dic_tmp.items())

#2- Main commands
subparsers = parser.add_subparsers(help='Choose a main command')
for d in dic:
    subparsers.add_parser(d,parents=dic[d]['parents'],help=dic[d]['help']).set_defaults(func=dic[d]['func'],auditType=d)

# ------------------------------------------- Parse arguments -------------------------------------------
args = dict(parser.parse_args()._get_kwargs())
arguments = parser.parse_args()
start_time = time.time()
output()
verbosity()

# ------ Part used for user impersonation ------ 

currentUser = getpass.getuser()
argv = vars(arguments)['auditType']
current_filepath = sys.argv[0]
sids = ListSids()
isSystem = False
stopExecute = True
isChild = isChildProcess(current_filepath)

There is some way to add from within the py the argument that I want to put.

    
asked by Perl 18.11.2016 в 18:40
source

1 answer

2

Good, in general to make the transfer of parameters via console is done through the library getopt that parsea the options of the command line, I show you through an example.

The piece of code that you want to execute is included inside a main function in the module that receives argv , for example:

# uso: test.py -i <inputfile> -o <outputfile>
import sys, getopt
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

Inside the module the following code is included that is executed only when the module is executed directly:

if __name__ == "__main__":
   main(sys.argv[1:])

Finally, if you want to run the module from another module of .py , you simply import the module with import file and you can pass the arguments from inside like this:

file.main("-i "file1" -o "file2"")

I wish that this was what you asked, in fact it seems to me that your question lacks information as to the depth that you gave to the problem. Anything I edit my answer, luck!

More information: link

    
answered by 18.11.2016 / 19:00
source