简体   繁体   English

我如何向使用subprocess.POPEN打开的进程提供命令并检索o / p

[英]how can i feed command to a process opened using subprocess.POPEN and retrive the o/p

My requirement is that I need to start a sqlcmd process and then feed the sql statement to that process and retrieve the output generated in that scenario. 我的要求是,我需要启动一个sqlcmd进程,然后将sql语句提供给该进程并检索在该场景下生成的输出。 Before you guys suggest me to use sql library to run sqlcmd let me tell you that I can't do that, I've a requirement to implement this using sqlcmd only. 在你们建议我使用sql库运行sqlcmd之前,让我告诉您我不能执行此操作,我要求仅使用sqlcmd来实现。

here is my current code 这是我当前的代码

from subprocess import Popen, PIPE

def ms_sql_session():
    IP = "xxxx"
    port = '1433'
    username = 'sa'
    password = 'abc'
    connString = 'sqlcmd -S tcp:%s,%s -dmaster -U%s -P%s ' %(IP, port, username, password)

    try:
        session = Popen(connString, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        str_cmd = '''select @@version;
        go
        '''
        session.stdin.write(str_cmd)
        stdout, stderr = session.communicate()
        print stdout
        print stderr
        str_cmd = '''select @@version;
        go
        '''
        session.stdin.write(str_cmd)
        #stdout, stderr = session.communicate()
        print stdout
        print stderr
        str_cmd = '''select @@version;
        go'''
        session.stdin.write(str_cmd)
        #stdout, stderr = session.communicate()
        print stdout
        print stderr
        return True
    except Exception, e:
        print str(e)
        return False

ms_sql_session()

I'm trying to execute 3 statement and retrieve the o/p but i'm getting the exception at the second stdin.write operation 我正在尝试执行3条语句并检索o / p,但在第二个stdin.write操作中却遇到了异常

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86) 
    Dec 10 2010 10:56:29 
    Copyright (c) 1988-2005 Microsoft Corporation
    Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 2)


(1 rows affected)


I/O operation on closed file

this is the output of my code. 这是我的代码的输出。

Why do you want to use a system cmd for that? 为什么要为此使用系统cmd? I would recommend to use an SQL library for that... 我建议为此使用SQL库...

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

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