[英]Python subprocess check_output return different result than running directly in terminal
[英]Running a py file through subprocess gives different output than running the file directly
我正在尝试使用subprocess
来生成一堆测试用例,但是出了点问题。 为什么以下(简化示例)不起作用?
我有第一个简单的程序sphere.py
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
PI = 3.141592
radius = float(input( 'Give the radius of the sphere (in cm): ' ))
area = 4*PI*pow(radius, 2)
volume = 4/3*PI*pow(radius, 3)
print("\narea: {} cm²\nvolume: {} cm³".format(round(area,2),round(volume,2)))
输入4
的结果(在运行python3 sphere.py
之后):
area: 201.06 cm²
volume: 268.08 cm³
然后我有另一个文件generator.py
运行第一个带有subprocess
的文件:
import subprocess
res = subprocess.run(["python", "sphere.py"], input="4",
capture_output=True, encoding="utf")
result_lines = res.stdout.split("\n")
for line in result_lines:
print(line)
但这会导致(不同的音量,运行python3 generator.py
之后):
Give the radius of the sphere (in cm):
area: 201.06 cm²
volume: 201.06 cm³
奇怪的是,当我将volume
公式更改为4.0/3.0*PI*pow(radius, 3)
时,它似乎工作正常......
这里发生了什么?
使用 Python 3.8
What usually happens on systems that have both Python 2 and 3 installed, is that python
command is linked to Python 2, and python3
is linked with... well obviously Python 3.
因此,当您从 shell 和 Python 3 运行文件时,子进程调用会调用 Python 2 解释器。 所以简单的解决方法是强制它使用 Python 3:
subprocess.run(["python3", "sphere.py"], ...)
或使用sys.executable
确保使用相同的 Python 解释器:
import sys
subprocess.run([sys.executable, "sphere.py"], ...)
或者,找到一种更好的方法来运行另一个文件的 Python 文件。
这个问题的提示是Python 2 和 3 之间的除法运算符的区别。 在 python 2 中, 4/3
/3 将给出 1。而在 Python 3 中,它将给出1.333
。 当您执行4.0/3.0
时,它强制 Python 2 解释器也使用浮点除法,因此问题得到解决。
有趣的是,使用4
作为输入使两个公式等效(在 Python 2 下)。 4/3
变成 1 并没有影响, radius
的额外幂等于乘以 4,因此结果相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.