subprocess.call无法按预期工作

时间:2013-05-20 08:49:33

标签: python windows batch-file subprocess

我有以下批处理文件(test.bat)

my.py < commands.txt

my.py执行以下操作:

import sys

print sys.stdin.readlines()

如果我从命令行(从Windows 7中的cmd.exe shell)启动此批处理文件,一切正常。

但如果我尝试通过python中的subprocess.call函数运行它,它就不起作用。

我如何尝试从python运行它:

import subprocess
import os

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

这是我收到的错误消息:

>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

我正在使用python 2.7.2但是在2.7.5我得到了同样的行为。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

应该是:

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

或者使用shell:

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

答案 1 :(得分:1)

这是否有效:

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()

我不确定你为什么提到:

my.py < commands.txt

输入是否与bat文件有关? 如果是,你打电话:

python my.py

通过子进程打开bat文件:

batfile < commands.txt

或为什么相关?