命令行和子进程之间的标准输入不一致。

2024-07-05 09:57:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个文件,作为python脚本的标准输入,并用子流程调用. 你知道吗

直接在命令行中执行时,效果很好:

输入文件:

# 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作为输入。你知道吗

是什么导致了这里的不一致?这两种方法不是等价的吗(显然不是,但为什么)?我的最终目标是执行与上述命令行版本完全相同的任务。你知道吗

谢谢


Tags: 文件命令行pytest脚本inputdatescript
3条回答

当使用input时,python2中的raw_inputeval字符串。如果使用python3运行脚本,它将按原样工作,因为python2将更改为raw_input。你知道吗

使用check_call通常是更好的方法,使用with打开文件。你知道吗

import subprocess
with open('test_input') as input1:
    subprocess.check_call(['python3', 'script.py'], stdin=input1)

所以切普纳是对的。当我修改下一行时:

subprocess.call(['python', 'script.py'], stdin=input1)

收件人:

subprocess.call(['python3', 'script.py'], stdin=input1)

效果不错。你知道吗

(我正试着用Python3做这个)

在第一个实例中,文件有两行,input()读取并解析第一行,这是一个注释。你知道吗

在第二种情况下,注释行丢失,因此Python读取并解析一个数字。你知道吗

您可能打算使用raw_input(),或者用python3运行脚本。你知道吗

(您可能还希望输入文件以换行符结束,并且在已经运行Python的情况下使用subprocess.call()来运行Python是没有意义的。)

相关问题 更多 >