![](/img/trans.png)
[英]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.