Passing values to a function from within a function in python

三世轮回 提交于 2019-12-13 23:48:12

问题


I need to pass values from one function to the next from within the function.

For example (my IRC bot programmed to respond to commands in the channel):

def check_perms(nick,chan,cmd):
  sql = "SELECT `"+ cmd +"` FROM permissions WHERE nick = '"+ nick +"' and chan = '"+ chan +"'" # This returns 0
  #sql = "SELECT `restart` FROM permissions WHERE nick = 'Me' and chan = '#mychan'" # this works as intended
  cursor.execute(sql)
  result = cursor.fetchall()
  for row in result:
     if (row[0] == 1): # Nick logged in and has permission
        return 1 
     else: # nick does not have permissions
        return 0

def com_restart(nick,chan):
  perm = check_perms(nick,chan,"restart")
  if (perm == 0): # nick did not have permission
     irc.send("NOTICE "+ nick +" :Permission denied.\n")
  elif (perm == 1): # nick has permission
     irc.send("PRIVMSG "+ chan +" :I've been asked to restart myself by "+ nick +".\n")

nick = "Me" # This is determined by a bunch of regex splits and such
chan = "#mychan" # This is determined by regex splits as well
com_restart(nick,chan)

When I try this, though, it seems the values do not get passed to the SQL query, so it returns 0.

Thanks for any help you can provide.

EDIT - Added code that I'm working with as it stands right now.


回答1:


What do you mean the string "sql" "returns zero" -- a string isn't a function or expression so it doesn't "return" anything. A string is just a literal value.

Are you saying that cursor.execute() returns zero? What is "cursor" equal to? Do you correctly initialize the "cursor" object to something somewhere else?

if "cursor" is a global object you may have to declare it as such, like this:

global cursor

otherwise you won't be able to make changes to it.

Other than that I can't figure out what you're doing or what's wrong.




回答2:


I'm not so sure about this line of code:

sql = "SELECT `"+ cmd +"` FROM permissions WHERE nick = '"+ nick +"' and chan = '"+ chan +"'" # This returns 0

It seems you're trying to make sure that the query strings are in proper format. But that's not necessary. You can concatenate your string query and it would work fine like this:

sql = "SELECT " + cmd + " FROM permissions WHERE nick = " + nick + " and chan = " + chan

Observe that there are no single quotes anywhere in the query statement.



来源:https://stackoverflow.com/questions/8829151/passing-values-to-a-function-from-within-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!