简体   繁体   English

Python 放入批处理脚本时文件未运行

[英]Python File is not running when put in a batch script

I have a python script that connect PostgresSQL.我有一个连接 PostgresSQL 的 python 脚本。

Below is the script.下面是脚本。

import psycopg2

conn = psycopg2.connect('connection string')
try:
  curr = conn.cursor()
  sql_strng = "SELECT * FROM tbl"
  ### Further operations###
except(Exception, psycopg2.Error) as error:
      print("error",error)
finally:
    if (conn):
       conn.close()

The above code works well when I run it from Spyder.当我从 Spyder 运行上面的代码时,它运行良好。 But when I try to run this from command prompt using a batch script it gives error as shown below.但是当我尝试使用批处理脚本从命令提示符运行它时,它会给出如下所示的错误。 My batch script:我的批处理脚本:

C:\Users\Anaconda3\python.exe \path\to\python\file

The above batch script is throwing error as follows.上面的批处理脚本抛出错误如下。

if(conn):
NameError: name 'conn' is not defined

Where I am missing out?我错过了什么?

You need to make the connection string global.您需要将连接字符串设为全局。 Also put an exception handler for the connection string as below:还要为连接字符串放置一个异常处理程序,如下所示:

try:
    conn = psycopg2.connect(connection string)
except Exception as e:
    print(e)

This will tell you if your connection has gone through or not这将告诉您您的连接是否已通过

If psycopg2.connect throws an exception, the conn =... assignment is never executed, which means that when you arrive at if (conn) , conn is still undefined.如果psycopg2.connect抛出异常,则永远不会执行conn =...赋值,这意味着当您到达if (conn)时, conn仍然是未定义的。

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

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