Executing other python scripts gives NameError exception - python

I have two .py scripts on the same folder, and I have a function like this on one:
def combat_menu():
exec("combat.py")
Theese scripts are named dungeon.py(the one im executing from) and combat.py.
When I execute this function this error appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\hp\Documents\piton\Dungeon\dungeon_Data\dungeon.py", line 25, in combat_menu
exec("combat.py")
File "<string>", line 1, in <module>
NameError: name 'combat' is not defined
I execute this function from a tkinter button widget like this:
event_button = t.Button(root, text="Open CM", command=combat_menu)
I have tried importing the code, but this gives ImportError.

The exec() function supports dynamic execution of Python code. It is not executing a shell command. To execute a shell command, in your case calling another python file. Instead you can use for example:
os.system(*cmd*) ->
os.system('combat.py')

Related

Exception has occurred: NoEntryPointError

I am using Discord.py, and while making a command handler using COG, I got this error.
This is the main.py (main bot file)
# Command Handler: Import cog files.
for file in os.listdir("./cogs"): # lists all the cog files inside the cog folder.
if file.endswith(".py"): # It gets all the cogs that ends with a ".py".
name = file[:-3] # It gets the name of the file removing the ".py"
client.load_extension(f"cogs.{name}") # This loads the cog.
Here is the link to the only file I have in my ./cog/ directory, named "Hellgoodbye.py".
https://pastebin.com/TdE8FPxq
The error I get when I do "python .\main.py" in my VSCode terminal, I get the following error:
Traceback (most recent call last):
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 612, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs.Hellogoodbye' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\main.py", line 141, in <module>
client.load_extension(f"cogs.{name}") # This loads the cog.
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 615, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.Hellogoodbye' has no 'setup' function
Can someone help me fix the error. i really do not know what is going on.
As the error says you don't have setup function. It is necesary for an extension to load.
import discord
from discord.ext import commands
class Name(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Name(bot))
This is an example of a cog file. As you can see at the very end of the code there is the setup function. It should be a standalone function which is not defined inside of the class.
Answer:
I moved
def setup(bot)
bot.add_cog(Hellogoodbye(bot))
To the end of the file, and it is working now, besides the fact I have some other issues, but the error I asked about is fixed by this.

Error while map reduce program in python

I am executing the Map reduce program in python on local system and getting the below error:
Password:Traceback (most recent call last):
File "./wordcount_mapper.py", line 7, in <module>
filename = os.environ["mapreduce_map_input_file"]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'mapreduce_map_input_file'
Check your environment variable mapreduce_map_input_file to see if it is set.
Type echo $mapreduce_map_input_file in your terminal. If it's not set the terminal won't print out anything.

Using pdb, how can I run a program and pause where reaching an error?

Using python interpreter and/or pdb, can we run a program and pause whenever reaching an error, so that I can examine all the frames of the call stack of the program at the time of crashing?
When I run a program directly inside python interpreter, when reaching an error, it tells where the line of code it happens, but it seems return to the topmost frame, and I can't examine the frame where the error actually happens. E.g.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 194, in <module>
addlevel(root_toc, 0)
File "test.py", line 191, in addlevel
addlevel(child, root_level+1)
File "test.py", line 188, in addlevel
root.value.append(root_level)
AttributeError: 'str' object has no attribute 'append'
>>> root_level
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'root_level' is not defined
The error happens at the lowest frame, and I can't examine the value of root_level at that frame. Is it because it returns to the topmost frame after the error happens? How can examine the lowest frame?
THanks.
Run pdb as a module, passing the script you want to debug. It will break on abnormal exits. (This is mentioned early in the docs.)
python -m pdb my_script.py
If you're in the interpreter, you can use pdb.pm() to debug the last traceback.
Or, use the IPython interpreter. Typing debug after an uncaught exception will enter a pdb session for the last traceback, similar to pm().

why `pdb` states something unrelated and misleading?

My Python script reports where it goes wrong ("line 122" in myscript.py), when I run it in a shell:
$ toc2others.py -i toc -p pg
Traceback (most recent call last):
File "~/myscript.py", line 122, in <module>
p = re.match(keywords[index+1][0], inlines[n+1], re.IGNORECASE)
IndexError: list index out of range
It is because keywords[index+1] goes out of the index range of keywords.
When I run it under pdb, however, it doesn't report where it goes wrong, but says something unrelated (error is reported to take place at import re).
$ pdb ~/myscript.py -i toc -p pg
> /myscript.py(3)<module>()
-> import re
(Pdb) c
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "~/myscript.py", line 3, in <module>
import re
IndexError: list index out of range
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
I wonder why pdb states something unrelated and misleading?
Can pdb state where it actually goes wrong?
Thanks.
It's a bug, actually.
See issues:
http://bugs.python.org/issue16482
http://bugs.python.org/issue17277
This only happens if exception is thrown on module-level of executed file, i.e. not inside any function. So if you just put your code in a main() function, this will fix it. Or you can use ipython, which is much more fun for debugging:
ipython ~/myscript.py --pdb -- -i toc -p pg
This will run the script and only stop if there's an error, and it also does not suffer from the above bug.

ConfigParser Error when running python script from RoR app's controller

I am trying to trigger a python script from a controller.
I have defined the follwing function in the controller:
private
def update_product_count(skus, qty)
system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py
skus qty > output"
end
Calling this function in another method of the same controller:
def show
//some code
update_product_count(#skus, #qty)
end
When I run the script manually, from my console, it runs fine. But i get this error when run from the controller:
Traceback (most recent call last):
File "/home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py", line 24, in <module>
devID = config.get("Keys", "Developer")
File "/usr/lib/python2.7/ConfigParser.py", line 607, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'Keys'
The most likely cause is that you are opening the config file using a relative path, and the controller has a different current directory to your console.
You should either use an absolute path to the config file, or have the script work out the directory it is executing in, and prepend that to the file name.

Categories

Resources