INS
INS

Reputation: 10820

subprocess.call doesn't 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 launch this batch file from command line (from cmd.exe shell in Windows 7).

But if I try to run it via subprocess.call function from python it doesn't 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 that 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'm using python 2.7.2 but on 2.7.5 I get the same behavior.

Any ideas?

Upvotes: 0

Views: 7608

Answers (2)

Torxed
Torxed

Reputation: 23500

Does this work:

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'm not sure why you refer to:

my.py < commands.txt

Does the input has anything to do with the bat-file? If so do you call:

python my.py

which opens the batfile via subprocess that does:

batfile < commands.txt

or why is that relevant?

Upvotes: 1

Inbar Rose
Inbar Rose

Reputation: 43507

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)

Upvotes: 4

Related Questions