Python: "global name 'time' is not defined"
By importing the function into another file before calling it, you're only importing the contents of that function. The imports at the top of that file are not imported into your other file. You should put both of your imports into the function so that it looks like this:
def knights_of_ni():
from time import sleep
import random
<the function contents>
This will verify that the imports that you want are available in the location that you call the function. There is no worry of double importing because python doesn't allow that - if time is imported in the file where this function is imported, it doesn't re
Apologies for the necropost but I ran into this problem too though in a slightly different way.
I was running time.time()
with mod_python under Apache and Python . If I attempted to load the page with time.time()
on it, it would fail complaining that "global name 'time' is not defined". However, if I ssh'd into my webserver and ran the exact same method from the command line, it would work.
In the end, restarting the Apache2 service fixed the issue. I'm not sure why this helped. I guess the module was unloaded at some point and then wouldn't reload, despite the import time command.
It's strange and a bit mysterious. Sorry I never hunted down the actual cause but hopefully this helps out the next person.
That's impossible. Your code example isn't the same as the code that produced that error.
Perhaps you had time.sleep(..)
instead of sleep(..)
. You have done from time import sleep
. To use the time.sleep(..)
form you must import time