Home > Enterprise >  Converting an argparse bash script into a python script
Converting an argparse bash script into a python script

Time:06-20

Consider the bash script below. The script argparse_test.py is an argparse script with various variables.

python -u argparse_test.py \
  --is_training 3 \
  --root_path ./dataset/ \
  --data_path data.csv \
  -/test_$seq_len'_'196.log 

How would I convert this bash script to a python script so that I could run it in a python IDE with the various variables?

CodePudding user response:

This bash input

python -u argparse_test.py \
  --is_training 3 \
  --root_path ./dataset/ \
  --data_path data.csv \
  -/test_$seq_len'_'196.log 

should produce a sys.argv that looks like

['argparse_test.py', '--is_training', '3', '--root_path ./dataset/','--data_path', 'data.csv', '-/test_$seq_len'_'196.log'] 

that's a rough guess; bash may be handling the slashes different (I'm on a windows machine now).

"running in an IDE" is a vague request.

Some IDE have a run menu item, and a way of specifying commandline arguments (usually in a separate menu setup item).

If you have code that setups up a parser:

parser = argparse.ArgumentParser(...)
...

the line

args = parser.parse_args()

reads that sys.argv[1:] and parses it. So an alternative way to use the parser is to provide the equivalent list of strings directly:

argv = ['--is_training','3',...]
args = parser.parse_args(argv)

If you can modify the script, you could add a couple of displays

import sys
print(sys.argv)

and after the parse_args

print(args)

args will be a argparse.Namespace object that should display like

Namespace(is_training=3, root_path='./dataset/', data_path='data.csv', ...)

vars(args)

is a dict with the same keys and values

Any python object with the same attributes should be have the same as args in the rest of your code.

I have a feeling this answer is too long and detailed - because of the vagueness of the question.

  • Related