【问题标题】:Python subprocess gives wrong value (gives 8bit value instead of 64 bit) [duplicate]Python子进程给出错误值(给出8位值而不是64位)[重复]
【发布时间】:2018-03-01 01:53:19
【问题描述】:

我正在 Python 中测试 subprocess 选项。我用 C 编写了简单的代码,我想通过 Python 中的子进程运行它。看起来是这样的:

C 代码 example.c(首先我执行代码,然后在子进程中使用可执行文件):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int number= 2110;

    while (1==1)
    {
        printf("%d",number);
        printf(" return number: ")
        return number;

    }
    return 0;
}

Python 代码:

def subTest():
    while True:
        numberS = subprocess.call('./example')
        print (numberS)

运行 python 代码后我应该得到的输出:

2110 return number: 2110

我得到的输出:

2110 return number: 62

我在一些“数字”和正确的值上测试它,我得到了 255 然后 256 -> 0 等等,这是为什么?为什么它给出 8bit 值以及如何返回正确的值?

【问题讨论】:

    标签: python c subprocess 64-bit 8-bit


    【解决方案1】:

    这不是 Python 的问题,而是 Linux 的一个特性。 Looking at this answer:

    目前,大多数基于 Unix 的系统仅支持 8 位返回值。 Windows 支持(至少)32 位返回值。

    因此,假设您使用的是 Unix,那么即使您有 int main(),返回值也被限制在 0 到 255 之间。同样来自链接问题:

    int main(void){
    return 256;
    }
    echo $? ;  # out 0
    

    您必须找到另一种方法来返回该值 - 也许将其打印出来? This answer shows how to do it:

    run = subprocess.Popen('./example', stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE, env={'LANG':'C++'})
    data, error = run.communicate()
    numberS = int(data)
    

    【讨论】:

    • 是的,我在 Raspbian 上,这很疯狂,只返回 8 位值。无论如何,如果我有 long long int main() 有同样的问题。但我使用你的代码,它给了我这个错误:ValueError: invalid literal for int() with base 10: b''
    • 您的代码应该有一个printf("%d", number);,正如您在问题中指出的那样。看起来好像你没有打印任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多