简体   繁体   中英

KeyError in python 3.6.4 in ec2

I am trying to run this python code on ec2 instance

   import os
   COMPUTER_NAME = os.environ['COMPUTERNAME']
       print("Computer: ", COMPUTER_NAME)

This is the error I get after running the code

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ec2-user/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None

I am trying to write my answer which helped me resolve this issue. Keeping in mind that it would be useful for someone with same issue.

import os
COMPUTER_NAME = os.environ.get('COMPUTERNAME')

This was done because I believe my environment has no computer name so instead of throwing a KeyError it will throw None.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM