1

My environment uses Python 2.6 and I'm new to Python. I need to write a script that runs a file decoding command which takes several arguments from the command line. My problem is I can't parse arguments taken from the terminal to the file decoding command.

For example if my program name is x.py and when i run "x.py Desktop/abc.txt" how can i pass Desktop/abc.txt as an argument to the cat command?

import commands
import sys

a=open("b.txt","w") 
a.write(commands.getoutput('cat sys.argv[1]'))

When i researched it seemed that the above program should work but it didn't. Please help.

mprat
  • 2,451
  • 15
  • 33
Amy
  • 23
  • 10
  • take a look at [calling-an-external-command-in-python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – luoluo Sep 12 '15 at 02:32
  • I did but it didn't help in this case. Contents of abc.txt must be there in the b.txt file but all it contains is "cat: sys.argv[1]: No such file or directory" – Amy Sep 12 '15 at 02:42

2 Answers2

1

You're mixing up the terminal commands and Python commands. If you have a file called abc.py with the following code:

import sys
print sys.argv[1]

And you run it with python abc.py arg1, it should print out arg1.

For a cleaner and easier to read way of using command-line arguments if you want to control things like make sure they are int or allow multiple or whatever, I've had a lot of success using the argparse module in Python - it's much easier to use than the sys.argv style of parsing command-line arguments. Check out the official tutorial / docs here: https://docs.python.org/2/howto/argparse.html

mprat
  • 2,451
  • 15
  • 33
  • The `getopt` module can be useful for defining acceptable options and arguments that can be passed to the program and filtering out unacceptable ones. – Rolf of Saxony Sep 12 '15 at 08:19
1

You should change commands.getoutput('cat sys.argv[1]') as commands.getoutput('cat %s' % (sys.argv[1],))

ellipse42
  • 100
  • 3
  • 1
    or even better `subprocess.check_output(["cat",sys.argv[1]]).read()` – Joran Beasley Sep 12 '15 at 02:48
  • @ellipse42 thanks a lot it solved my problem :) Say cat takes 4 arguments – Amy Sep 12 '15 at 02:53
  • 1
    Say cat takes 4 arguments where 2 of them are integers, 1 is a string and 1 is a variable named log which has read contents of a file to it. So is it ('cat %s%s%d%d' % (sys.argv[1], log,sys.argv[1],sys.argv[2])) – Amy Sep 12 '15 at 02:59