Home > Blockchain >  Python: subprocess isql on windows: a bytes-like object is required, not 'str'
Python: subprocess isql on windows: a bytes-like object is required, not 'str'

Time:12-08

This is a company issued laptop and I can't install any new software on it. I can install Python modules to my own directory though. I need to run something on Sybase and there are 10 servers. Manual operation is very time consuming hence I'm looking for the option as Python subprocess.

I did some research and referred to using subprocess module in python to run isql command. However, my version doesn't work. The error message is TypeError: a bytes-like object is required, not 'str'. This error message popped up from the "communicate" line.

I can see my "isql" has connected successfully as I can get a isql.pid.

Anything I missed here?

Thank you

import subprocess
from subprocess import Popen, PIPE
import keyring
from textwrap import dedent

server = "MYDB"
cmd = r"C:\Sybase15\OCS-15_0\bin\isql.exe"
interface = r"C:\Sybase15\ini\sql.ini"
c = keyring.get_credential("db", None)
username = c.username
password = c.password

isql = Popen([cmd, '-I', interface,
              '-S', server,
              '-U', username, 
              '-P', password,
              '-w', '99999'], stdin=PIPE, stdout=PIPE)
output = isql.communicate("""\
    SET NOCOUNT ON
    {}
    go
""".format("select count(*) from syslogins"))[0]

CodePudding user response:

From the communicate() documentation,

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

By default, streams are opened in binary format, but you can change it to text mode by using the text=True argument in your Popen() call.

  • Related