[Python] python calling executable with popen;, file written by executable can not be accessed

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I have a C++ file

    #include <cstdio>

    int main(int iArgC, char *apArgV[]) {
    int iResult = -1;
    if (iArgC > 1) {
    FILE *fOut = fopen(apArgV[1], "wt");
    if (fOut != NULL) {
    fprintf(fOut, "hello\n");
    fprintf(fOut, "goodbye\n");
    fclose(fOut);
    printf("Written `%s`\n", apArgV[1]);
    iResult = 0;
    } else {
    printf("Coudn´t open %s\n", apArgV[1]);
    }
    } else {
    printf("I need an argument\n");
    }
    return 0;
    }


    which i compile like this

    g++ -g -o hello hello.cpp


    When i run ./hello /home/jody/hihi,txt the file hihi.txt is written.

    Then i have this python script

    #!/usr/bin/python

    import subprocess as sp
    import time

    def callHello(file_name) :
    command = ["/home/jody/progs/polyhedronLED/version_c/hello", file_name]
    proc = sp.Popen(command,
    stdout=sp.PIPE,
    stderr=sp.PIPE)
    sOut, sError = proc.communicate()
    iResult = proc.returncode
    print("return code: %d"%iResult)
    print("Output: %s"%sOut)
    # -- end def

    if __name__ == '__main__':
    file_name0 = "/home/jody/hihi.txt"
    callHello(file_name0)

    ff = open(file_name0, "wt")
    lines = ff.readlines()
    ff.close()
    print("output\n%s"%lines)
    # -- end if


    When i run this script, i get the output:

    return code: 0
    Output: b'Written `/home/jody/hihi.txt`\n'
    Traceback (most recent call last):
    File "/home/jody/progs/polyhedronLED/version_c/./hellocall.py", line 22, in <module>
    lines = ff.readlines()
    ^^^^^^^^^^^^^^
    io.UnsupportedOperation: not readable


    But when i subsequently check the output directory, the file hihi.txt has been written.

    I also tried it with a delay time.sleep(5) after the call to callHello() but the result was the same.

    I then wrote a bash script which calls hello and subsequently reads the contents of the file: this worked as expected.

    When (or how) can a file written by a subprocess be actually accessed in python?

    Continue reading...

Compartilhe esta Página