0

I am using Popen from subprocess library and wish to pass a variable to popen.stdin.write for executing a bat file. I wish to execute my bat file by

C:\Users\7zx3we\test.bat chinni

Mycode


from subprocess import Popen,PIPE

p = Popen('cmd.exe ', stdin=PIPE, stdout=PIPE)
name = 'chinni'
p.stdin.write('C:\Users\7zx3we\test.bat ' + name + '\n')

But this is giving me a syntax error and failing to run. What can I try to resolve that?

halfer
  • 19,824
  • 17
  • 99
  • 186
chink
  • 1,505
  • 3
  • 28
  • 70
  • Best to include (verbatim) any errors you get with your question but you'd probably need to use raw strings, e.g., `r'C:\Users\7zx3we\test.bat '` since the `'\t'` is a tab character. –  Mar 03 '21 at 14:21
  • Additionally (next to @JustinEzequiel 's comment), you're only importing `Popen`, but you'll also need to import `PIPE` from `subprocess` – Giuseppe Accaputo Mar 03 '21 at 14:23
  • I'm importing `PIPE` too. made the edit – chink Mar 03 '21 at 14:26

1 Answers1

0

Two things:

  1. You need to define the encoding if you want to open stdin in text mode. You can do this by specifying the encoding parameter:
Popen('cmd.exe`, stdin=PIPE, stdout=PIPE, encoding='utf8')
  1. You need to escape the backslashes in the path, since otherwise they will be evaluated to a wrong value, e.g., \U starts a Unicode escape sequence and \t is the tab character:
p.stdin.write('C:\\Users\\7zx3we\\test.bat ' + name)
Giuseppe Accaputo
  • 2,642
  • 17
  • 23