Click here to Skip to main content
15,889,635 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am facing problem in error in my programs


I am not able to understand what I am doing mistake .

What I have tried:

def Runcommand(self, data):
      command = data
      #command = self.read()
      stdoutOrigin=sys.stdout
      try:
          sys.stdout = open("command1.txt", "w")
          exec(command)
          sys.stdout=stdoutOrigin
          with open("command1.txt","r") as f:
              result =  f.read()
              print(result)
              self.write(result.encode())
      except Exception as e:
          s=str(e)
          error=''.join((s,'\n'))
          self.write(error.encode())
      finally:
          f.close()




error was
local variable 'f' referenced before assignment
Posted
Updated 4-Sep-22 20:50pm

1 solution

When you create a variable, it has Scope - it is only visible or usable within the block it is created in.
Wo when you create a variable called f inside a try block, it's scope is restricted to the block, and it cannot be referenced outside it as it is destroyed when you leave the block by whatever method. To access it outside the try block, you would have to declare f before the try statement, at which point it is accessible to all code in the method.

In fact, the with statement automatically closes the file when you exit the with block for you, so the whole finally block is redundant, and can be removed - which solves the problem more neatly!
 
Share this answer
 
Comments
CPallini 5-Sep-22 3:28am    
5.
HelpMewithCode 6-Sep-22 1:10am    
Thank you
OriginalGriff 6-Sep-22 1:26am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900