简体   繁体   English

Python - function 调用 exec() 看不到变量

[英]Python - function calling exec() does not see variable

I have following script that works well on it's own, but once I wrap it all into a function does not return data.我有以下脚本,它自己运行良好,但是一旦我将它全部包装到 function 中,就不会返回数据。 The command changes based on input data structure.该命令根据输入数据结构而变化。 This is an example of the command I want to feed into the exec():这是我要输入 exec() 的命令示例:

cross_data=pd.crosstab(src_data['result'],[src_data['c1'],src_data['c2']],normalize='index')

This is my function I want to wrap the code in and call:这是我的 function 我想将代码包装进去并调用:

    def calcct(file_path='src_data.csv', separator = ",", res_col = 'result'):    
        #define function

        src_data = csv_import(file_path, separator) #import data
        reorder_cols = reorder_columns(src_data, res_col) #work with data
        head_list=list(reorder_cols.columns.values) #get dataframe headers

        # create command based on headers and execute that. Should return dataframe called cross_data.
        exec(crosstabcmd(head_list)) 
        return cross_data

Results in:结果是:

NameError: name 'cross_data' is not defined

I cannot seem to find the correct syntax for calling exec inside a function. I tried defining and passing the cross_data variable, but I just get an error it doesnt see pandas when I do that.我似乎找不到在 function 中调用 exec 的正确语法。我尝试定义并传递 cross_data 变量,但我只是收到一个错误,当我这样做时它没有看到 pandas。

Or is there some better way?或者有更好的方法吗? I need to compose the command of 2-x column names, count and names of columns are variable.我需要编写 2-x 列名的命令,列的计数和名称是可变的。

First up第一

You probably don't mean to be using exec - that's a pretty low-level functionality.您可能并不是要使用exec - 这是一个非常低级的功能。 There isn't really enough context to understand how to fix this yet.还没有足够的上下文来理解如何解决这个问题。 Could you write out (in your question) what the crosstabcmd function looks like?你能写出(在你的问题中) crosstabcmd的样子吗?

The error错误

NameError: name 'cross_data' is not defined

is because you've never defined a variable called cross_data in the scope of function calcct , ie you have never done cross_data = "something" .是因为您从未在 function calcct 的calcct中定义名为cross_data的变量,即您从未做过cross_data = "something"

I'll give it a go我会给它一个 go

Assuming you have something like假设你有类似的东西

import pandas as pd

def crosstabcmd(head_list):
    # ? I can only guess what your crosstabcmd does, this won't work though
    return pd.crosstab(*head_list, normalize='index')

then the solution would look like:那么解决方案将如下所示:

def calcct(file_path = 'src_data.csv', separator = ",", res_col = 'result'):
    src_data = csv_import(file_path, separator) #import data
    reorder_cols = reorder_columns(src_data, res_col) #work with data
    head_list=list(reorder_cols.columns.values) #get dataframe headers
    cross_data = crosstabcmd(head_list)
    return cross_data

In my case I had main script which called a second script.在我的例子中,我有一个调用第二个脚本的主脚本。 I needed to use the "c" variable within the second script.我需要在第二个脚本中使用“c”变量。 Therefore I used locals(),loc as arguments for exec().因此,我将locals(),loc用作 exec() 的 arguments。

loc = {}
a = 10
b = 5
def abc(a,b):
    qwerty = "c = %d + %d"%(a,b)
    exec(qwerty, locals(), loc)
    c = loc['c']
    d = c+2
    print(d)

abc(a,b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM