Hamid K
Hamid K

Reputation: 1165

os.system to subprocess.Popen or subprocess.call

I have a function as below which is working fine when I execute my python code in CMD (SIMT is an executable). However, when I built my executable with py2exe, a shell window quickly appear and disappear. So I searched and found out that I can use the subprocess.popen with creationflags= 0x08000000. But it does not work.

This is my function

def Kill(SIMT):
  outfile1 = open('Kill.txt', 'w')
  outfile1.write('Kill' + '\r\n')
  outfile1.write('x')
  outfile1.close()
  os.system("type Kill.txt | testclient p . " + SIMT)
  os.remove('Kill.txt')

and I replaced the os.system with:

  subprocess.Popen(["type Kill.txt | testclient p . ", SIMT], creationflags= 0x08000000, shell=True).communicate()

Also, do I need to have the shell=True?

Upvotes: 0

Views: 738

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882271

If you want the shell to arrange the pipeline for you, you do need to have shell=True and have the first argument be a string, just like you had it for os.system, not a list. With shell=False, the list means to execute the program given as the list's first item, with the other items as command-line arguments to it; so you can't have the first item contain a | and expect the shell to arrange on your behalf that pipeline.

Your alternative is to arrange the "pipeline" or its equivalent yourself -- e.g, probably simplest here, just have a file object opened on Kill.txtas the standard input (stdin=) of the subprocess.Popen which only executes testclient (I believe type does nothing but read the file out to stdout, so that should suffice for this specific use case).

Upvotes: 1

Related Questions