【发布时间】:2015-06-19 08:27:59
【问题描述】:
我想创建一个文件,用作 python 脚本的标准输入,并使用 subprocess.call 调用该脚本。
当我直接在命令行中执行它时,它工作正常:
输入文件:
# test_input
1/2/3
python 脚本
# script.py
thisDate = input('Please enter date: ').rstrip()
以下命令可以正常工作:
python script.py < test_input
但是当我尝试从另一个 python 脚本中执行以下操作时,它不起作用。 (来自this)
outfile1 = open('test_input', 'w')
outfile1.write('1/2/3')
outfile1.close()
input1 = open('test_input')
subprocess.call(['python', 'script.py'], stdin=input1)
然后我收到以下错误:
>>>thisDate = input('Please enter date: ').rstrip()
>>>AttributeError: 'int' object has no attribute 'rstrip'
当我进行一些调试时,它似乎将整数 0 作为输入。
是什么导致了这里的不一致?这两种方法是否不等效(显然它们不是,但为什么)?我的最终目标是执行与上述命令行版本完全相同的任务。
谢谢
【问题讨论】:
-
听起来像是 Python 2 与 Python 3 的问题。在 Python 2 中,
input将在返回结果之前将字符串计算为两个整数除法;您通常会改用raw_input。在 Python 3 中,input的行为类似于(并替换)raw_input。 -
你是 100% 正确的。我将在编辑中反映我的解决方案。
标签: python subprocess stdin