如何在python

时间:2015-07-23 17:49:38

标签: python python-2.7

我在spyder ide中编写了代码并将其命名为test1.py并编写了另一个代码,我在其中调用了第一个代码。

第一个代码:

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                "database":"master", \
                "uid":"sa", \
                "pwd":"secret" \
               }
    print buildConnectionString(myParams)   

第二段代码:

import test1

Params = {"server":"mpilgrim", \
            "database":"master", \
            "uid":"sa", \
            "pwd":"secret" \
         }

print test1.buildConnectionString(Params)   

但我得到一个错误print buildConnectionString(myParams) NameError: name 'myParams' is not defined

3 个答案:

答案 0 :(得分:1)

如果文件作为模块导入(.noclick),

$(document).on('click', function (e) { if (!$(e.target).closest('.noclick').length) { alert('Alert'); } }); 将不会是__name__,因此永远不会定义"__main__"

答案 1 :(得分:0)

导入python模块时,需要在模块目录中有一个(function() { 'use strict'; /** * @ngdoc function * @name gemStoreApp.controller:ReviewCtrl * @description * # ReviewCtrl * Controller of the gemStoreApp */ angular.module('gemStoreApp') .controller("ReviewCtrl", ['$scope', 'Restangular', 'productsService', function ($scope, Restangular, productsService) { this.review(); this.addReview = function(product){ this.review.createdOn = Date.now(); var productReview = Restangular.all('/products/' + product._id + '/reviews'); productReview.post(product).then(function(newResource){ }); }; })(); 文件(它可以为空)。

你的缩进看起来很时髦,但我假设这是格式化的。

See the modules docs for python

答案 2 :(得分:0)

压痕。我的猜测是,您运行的代码仍然存在此处发布的代码的缩进问题。

导入文件的最后一行

print buildConnectionString(myParams) 

需要缩进到

if __name__ == '__main__':

块。否则,它会在导入时尝试在未定义myParams dict时执行。

相关问题