1

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

Nim
  • 158
  • 2
  • 14

1 Answers1

1

.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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Je suppose que tu est français vu ton nom, ça tombe bien, moi aussi ^^. Haha, quel idiot, j'avais complètement oublié os.getenv ==". Je vais utiliser ça, mais sinon, j'ai résolu mon problème. C'était a cause du sys.stdout.encoding, vu que c'est en arrière plan il n'y a pas de stdout ^^". Sans ça ça marche, mais je vais quand même utiliser os.getenv(), plus clean. Merci! – Nim Oct 04 '17 at 14:01
  • oui, c'est mieux! yes it's better. – Jean-François Fabre Oct 04 '17 at 14:03