73install_files += init_scripts
74
75def read(fname):
76 with open(os.path.join(os.path.dirname(__file__), fname)) as f: 77 return f.read()
78
79try:
49def getCpuUsage():
50 global lastUsage, lastUsageTime
51
52 rusage = getrusage(RUSAGE_SELF) 53 currentUsage = rusage.ru_utime + rusage.ru_stime
54 currentTime = time.time()
55
594 Read settings for 'program' from configuration file specified by
595 'options["config"]', with missing values provided by 'defaults'.
596 """
597 settings = Settings()598 settings.update(defaults)
599
600 # Initialize default values if not set yet.
496 raise SystemExit(1)
497
498
499def get_default_parser(usage="%prog [options] <start|stop|status>"):500 """Create a parser for command line options."""
501 parser = OptionParser(usage=usage)
502 parser.add_option(
104 return
105
106 if hasattr(protocol, 'datagramReceived'):
107 service = CarbonService(interface, port, protocol, None)108 else:
109 factory = CarbonReceiverFactory()
110 factory.protocol = protocol
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()