簡體   English   中英

通過子進程運行 py 文件與直接運行文件給出不同的 output

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM