Reputation: 1244
Am experiencing a bizarre problem with my python script the file is being red twice.
Script:
import platform as serverPlatform
class platform:
@staticmethod
def kernel():
return serverPlatform.release()
@staticmethod
def cpu():
with open('/proc/cpuinfo', 'r') as f:
print("x")
for line in f:
if line.strip():
if line.rstrip('\n').split(':')[0].startswith('model name'):
model_name = line.rstrip('\n').split(':')[1]
print platform.cpu()
The code above prints "x" twice:
[root@localhost lib]# python platform.py
x
x
However if i remove the class and run the code found inside the cpu()
method directly it prints me "x" only once.(python script without the class)
with open('/proc/cpuinfo', 'r') as f:
print("x")
for line in f:
if line.strip():
if line.rstrip('\n').split(':')[0].startswith('model name'):
model_name = line.rstrip('\n').split(':')[1]
What am I doing wrong in my initial script and why is it printing me "x" twice? Thanks in advance
UPDATE
Ok I realised my mistake as silly as it may sound I imported the module platform in a script containing the custom class names platform. So i changed the name of the class from platform to platforms
import platform as serverPlatform
class platforms:
@staticmethod
def kernel():
return serverPlatform.release()
@staticmethod
def cpu():
with open('/proc/cpuinfo', 'r') as f:
print("x")
for line in f:
if line.strip():
if line.rstrip('\n').split(':')[0].startswith('model name'):
model_name = line.rstrip('\n').split(':')[1]
print platforms.cpu()
Upvotes: 0
Views: 1918
Reputation: 659
while importing python scripts, it will execute all the statements, like function declaration, class declaration and executable statements (like print). So when you import flatform it will execute flatform.cpu()
once. and one more call from the file in which you imported.
Upvotes: 2