1

I have a python script func.py that contains argparse and takes a file

parser = argparse.ArgumentParser(description='test')
parser.add_argument('-i', dest='ifile', metavar="FILE", help='input file')
args = parser.parse_args()

This ifile is basically just a name of that file in a directory

filename = 'PATH TO FILE' + args.ifile

If I have a variable that contains the name of the file how can I pass the variable to the argparse so that it would take the string value of the variable? Something like this :

new_file = 'text_file.txt'
func.py -i new_file
filename = 'PATH TO FILE' + 'text_file.txt'

What I am getting now is this:

new_file = "text_file.txt'
python func.py -I new_file
filename = 'PATH TO FILE' + 'new_file'

And then obviously an error message that it cannot find the file.

4
  • Can you post a more detailed example? I cant even figure out where are those lines coming from Commented Dec 14, 2018 at 0:37
  • For what reason do you want the command line argument to refer to a variable name? I suspect that you are going the wrong way to solve whatever problem you are trying to solve. Commented Dec 14, 2018 at 0:37
  • @user10605163 I need to run func.py inside jupyter notebook (! func.py -i new_file) Unfortunately there is no other way I can run this script Commented Dec 14, 2018 at 0:41
  • Please add Jupyter to the question. Normally this isn't a problem in python. Commented Dec 14, 2018 at 0:43

1 Answer 1

2

You should simply be able to do:

$ new_file="text_file.txt"
$ ./func.py -I $new_file

Your args variable in Python should then contain ifile='text_file.txt':

text_file.txt
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.