Question

I must run the exact command:

python3 main.py flip pattern.ppm > flippedpattern.ppm

on the following code:

def main(args):
    if sys.argv[1] == "flip":
        fileName = sys.argv[2]
        method = read_ppm(fileName)
        print(method.flip())
        return
if __name__ == '__main__':
    sys.exit(main(sys.argv))

I have a ppm file and I am trying to manipulating it using another module, but it keeps telling me sys.argv[4] is out of range when assigning it to the variable 'outputFile'

The code executed should be essentially this for the flip command

method = "flip"
method = read_ppm("pattern.ppm")
f.write(method.flip())

Doing exactly that using the repl in visual studio leads to success but when I try to run it from the command line through the main module it doesn't work. Why is this? Does the '>' character somehow interfere with sys.argv or am I making a clear counting mistake that I can't see?

The else statement would account for the input not catching and simply printing, using the input

python3 main.py flip pattern.ppm

without any file redirect.

Was it helpful?

Solution

The argument after > is not part of the command line passed to python. It is the file that the shell writes standard output to. So, for example, print "Hello" will write Hello to flippedpattern.ppm.

If you want flippedpattern.ppm to be the fourth command line argument, just leave out the > in the call. (Then, standard output will be written to the screen.)

Edit: Given your modified description, you can write sys.stdout.write(method.flip()). The only difference between this and print(method.flip()) is that print adds a newline character at the end of the string, while .write doesn't.

OTHER TIPS

I'm not sure how Visual Studio works, but if it works with argv[4] it's probably interpreting every word after the script name like another argument (as it's not bash to have a special interpretation for ">").

So for it to work from bash, you should probably change argv[4] in the code to argv[3], and pass the output file as another argument instead of redirecting:

python main.py flip pattern.ppm flippedpattern.ppm

, or leave the code as it is and add a "dummy" third argument so the output file will be the 4th, for example force it to treat ">" as a regular argument as well:

python3 main.py flip pattern.ppm ">" flippedpattern.ppm
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top