Subprocess.call does not work as expected

I have the following batch file (test.bat)

my.py < commands.txt 

my.py does the following:

 import sys print sys.stdin.readlines() 

Everything works fine if I run this batch file from the command line (from the cmd.exe shell on Windows 7).

But if I try to run it using the subprocess.call function from python, this will not work.

How I try to run it from python:

 import subprocess import os # Doesn't work ! rc = subprocess.call("test.bat", shell=True) print rc 

And this is the error message I get:

 >my.py 0<commands.txt Traceback (most recent call last): File "C:\Users\.....\my.py ", line 3, in <module> print sys.stdin.readlines() IOError: [Errno 9] Bad file descriptor 1 

I am using python 2.7.2, but on 2.7.5 I get the same behavior.

Any ideas?

0
source share
2 answers

It should be:

 rc = subprocess.call(["cmd", "/c", "/path/to/test.bat"]) 

Or using the shell:

 rc = subprocess.call("cmd /c /path/to/test.bat", shell=True) 
+2
source

It works:

 from subprocess import * rc = Popen("test.bat", shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE) print rc.stdout.readline() print rc.stderr.readline() rc.stdout.close() rc.stdin.close() rc.stderr.close() 

I am not sure why you are referencing:

 my.py < commands.txt 

Does the input have anything to do with the bat file? If so, you call:

 python my.py 

which opens the bat file through a subprocess that does:

 batfile < commands.txt 

or why is it relevant?

+1
source

Source: https://habr.com/ru/post/1499256/


All Articles