0

I would like to to create a var with subprocess.Popen and read the content of the var.

I don't know how to use subprocess.Popen correctly, I tried :

p1 = subprocess.Popen('set var="something"', shell=True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
p2 = subprocess.Popen('echo var %var%', shell=True, stdin = p1.stdout, stdout = subprocess.PIPE)
p1.stdout.close()
out, err = p2.communicate()
print(out)

Output :

b'var %var%\r\n'

Any idea on how to do that ?

Mairkur
  • 125
  • 10
  • Each process has its own environment, which by default is a copy of its parent's environment. Thus `var` defined in the `p1` cmd.exe instance is not defined in the `p2` cmd.exe instance. You can define it in the current Python process via `os.environ['var'] = 'something'`. – Eryk Sun Jul 30 '19 at 14:17
  • It works ! Do you know a way to "inject" command in the first cmd.exe directly ? – Mairkur Jul 31 '19 at 08:34
  • Do you mean that you want to interact with a single instance of cmd.exe? That works as long as you're only running internal commands such as `dir` or non-interactive external commands such as `attrib.exe` . But you'll run into problems in general if you try to run another interactive console process from that shell. The problem is the fact that the standard streams are pipes. Programs switch to full buffering when standard I/O is a pipe or disk file, and a stream buffer is typically 4 KiB and only flushes when full. As you can imagine that prevents interactive use. – Eryk Sun Jul 31 '19 at 09:37
  • Yes that's what I meant. Thanks for the explanation. – Mairkur Aug 01 '19 at 08:41

0 Answers0