Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python KeyError: 'OUTPUT_PATH'

Tags:

python

I'm trying to run the following python code for to exercise

#!/bin/python3

import os
import sys

#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
    return n+1

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        n = int(input())

        result = maximumDraws(n)

        fptr.write(str(result) + '\n')

    fptr.close()

but i get this error message

Traceback (most recent call last):
  File "maximumdraws.py", line 13, in <module>
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
  File "/home/inindekikral/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'OUTPUT_PATH'

My Operation System is Linux Mint 19 Cinnamon. What i have to do?

like image 575
Batuhan Özkan Avatar asked Dec 02 '22 10:12

Batuhan Özkan


2 Answers

I'm sure there are other ways to do this, but for Hackerrank exercises, the file pointer was opened this way:

fptr = open(os.environ['OUTPUT_PATH'], 'w')

... and I want it to just go to standard output.

I just changed that line to

fptr = sys.stdout   # stdout is already an open stream

and it does what I want.

Note that on the one hand, os.environ['OUTPUT_PATH'] is a string, while fptr is a stream/file pointer.

Variations:

  1. If you want to write to a file, you can do it the way suggested above (setting the OUTPUT_PATH environment variable).

  2. Or, you can set the os.environ directly in python, e.g.

    os.environ['OUTPUT_PATH'] = 'junk.txt' # before you open the fptr!

like image 152
redpixel Avatar answered Dec 28 '22 02:12

redpixel


os.environ lets you access environment variables from your python script, it seems you do not have an environment variable with name OUTPUT_PATH. From the terminal you run your python script, before running your python code set an environment variable with name OUTPUT_PATH such as:

export OUTPUT_PATH="home/inindekikral/Desktop/output.txt"

Your python script will create a file at that location.

like image 21
unlut Avatar answered Dec 28 '22 02:12

unlut