pythonsocketssubprocessbackground-processpythonw

Python pythonw subprocess check_output not working


I have a problem regarding pythonw. I'm making a program which should be executed in background. When it starts, it's supposed to send the computername, the username and the result of a check to see if the program has admin rights. Here's the relevant piece of the client code:

computername = subprocess.check_output("echo %computername%", shell=True).decode(sys.stdout.encoding).splitlines()[0]
username = subprocess.check_output("echo %username%", shell=True).decode(sys.stdout.encoding).splitlines()[0]
isadmin = ctypes.windll.shell32.IsUserAnAdmin()
sleep(0.5)
s.send(computername.encode() + ";;".encode() + username.encode() + ";;".encode() + str(isadmin).encode())

And this is the piece of server code that's supposed to receive it:

data = conn.recv(1024).decode().split(";;")
print(data)
clientcount += 1
clientlist.append({"conn": conn, "ip": ip, "id": clientcount, "name": data[0] + "\\" + data[1], "isadmin": int(data[2])})

(the print line is just for debug) So here's the problem. When I execute the client code as client.py, everything works normally, I get this output:

['DESKTOP-#######', '######', '0']

and the code can go on. But when I execute the program as client.pyw, as it's supposed to be, I get:

['']

So of course I get an IndexError. I'm guessing something goes wrong with the subprocess.check_output. Is it normal? With what could I replace it, so it works in background?

(I'm using python 3.5)

Thanks


Solution

  • .pyw doesn't have a console, so there's an issue with subprocess when running pythonw without redirection of stdin (as explained in the duplicate that I just digged out).

    In your case, adding stdin=subprocess.PIPE,stderr=subprocess.STDOUT solves the issue, by providing valid streams for input & errors.

    But, above all:

    subprocess.check_output("echo %computername%", shell=True).decode(sys.stdout.encoding).splitlines()[0]
    

    is really overkill for

    os.getenv("computername")
    

    that that will work with pythonw so do that, it's cleaner, and it will definitely solve your problem.