我正在尝试使用 Python 3 创建一个新进程,以便在“同一会话”中运行多个命令,因为只打开了一个控制台窗口。它与存储在内存中的 DB2 LUW 数据库有关。我使用以下代码创建了一个名为“winshell.py”的文件:
import sys
import subprocess
def shell_execute(cmd, filename=""):
'''
Executes a command on SO and returns STDOUT and STDERR to a variable.
If filename is used, then write STDOUT and STDERR to a file.
'''
try:
output = subprocess.check_output(cmd, shell=True)
str = output.decode("1252")
str = str.replace("\r","")
if filename:
file = open(filename, "a")
file.write(str)
file.close()
return "Output sent to file: "+filename
else:
return str
except subprocess.CalledProcessError as cpe:
str = cpe.output.decode("1252")
if filename:
file = open(filename, "a")
file.write(str)
file.close()
else:
return str
except Exception as ex:
format(ex)
然后我从另一个 Python 程序运行:
winshell.shell_execute( 'db2 "CONNECT TO AGRIA"', filename )
winshell.shell_execute( 'db2 "CONNECT RESET"', filename )
winshell.shell_execute( 'db2 "CONNECT TERMINATE"', filename )
返回的代码是:
Database Connection Information
Database server = DB2/NT64 10.5.0
SQL authorization ID = DB2ADMIN
Local database alias = AGRIA
SQL1024N A database connection does not exist. SQLSTATE=08003
DB20000I The TERMINATE command completed successfully.
显然,它成功地运行了连接语句,但是在完成时连接就丢失了。在控制台提示符下,这 3 个命令完美运行。
有谁知道如何在控制台中创建一个会话作为单个进程/线程?