-2

I want to use sys.argv to access the arguments passed to the script. Here is my code :

if __name__ == '__main__':
    data = {}
    if len(sys.argv) >= 2 :read_inputs(data, sys.argv[1])
    else : print "ERROR : the config file is required in the command line"

    if len(sys.argv) >= 3 :data['Parameters']['Mode'] = sys.argv[2]
    print_data(data)
  • I understand that sys.argv[1] and sys.argv[2] refer to the arguments.
  • My arguments are contained in a text file.

What I cannot understand is how can I tell the code that it needs to read the arguments in that exact text file. I used python Interface.py config.txt but it didn't work.

Any ideas ?

AmyMagoria
  • 159
  • 7
  • 2
    Are you expecting Python to magically guess that `argv[1]` contains a file it should go and (somehow) read to get arguments? That is **not** going to happen. – jonrsharpe Mar 18 '15 at 10:22
  • You should open that file with `open()` and read data from there. What is your problem? Or you may use shell (if you working with nix-like System) to help you reading arguments like `python Interface.py $(cat config.txt)` – myaut Mar 18 '15 at 10:22
  • Read that file in your code. Refer this link for the examples: http://www.tutorialspoint.com/python/python_files_io.htm – Prerak Sola Mar 18 '15 at 10:23
  • So I opened the file like this : `obj = open("config.txt","r")` like it says in the link. Then I did this: `sys.argv[0] = obj.name` But it didn't work. @PrerakSola @myaut – AmyMagoria Mar 18 '15 at 10:37
  • `obj.name` returns you the file name. You need to use `read()` or `readLine()` to read the contents. There are examples of it in the link I gave. Scroll down further and you'll find it. – Prerak Sola Mar 18 '15 at 10:44

2 Answers2

1

If I understand you correctly you want what would normally be on the command line to be in that file, right?

You can do that using command substitution python Interface.py $(< config.txt), as seen here

Community
  • 1
  • 1
greschd
  • 606
  • 8
  • 19
1

Although not a direct answer to your question, I would highly recommend using the Python argparse module to parse command line argument. I your case I would add a "-c, --config" option that specifies the location of the config file that you want to use. See the documentation for examples: https://docs.python.org/3/library/argparse.html

Marco Nawijn
  • 137
  • 2