#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    12
    Rep Power
    0

    Help with Python subprocess module using files as stdin and stdout


    Specifically, how do I replicate the following batch command using python subprocess module?:

    Code:
    myprogram<myinput.in > myoutput.out
    If you don't know, I am trying to run myprogram using the contents of myinput.in as the standard input and myoutput.out as standard output.

    (myprogram is written in c and I/O with scanf, printf) So far I have tried the following:

    Code:
    myinput = open('myinput.in')
       myout = open('myoutput.out')
       p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput, shell=True)
       p.wait()
       myoutput.flush()
    And also,

    Code:
    myinput = open('myinput.in')
       myout = open('myoutput.out')
       inputs = myinput.read()
       myinput.close()
       myprogram = subprocess.Popen('myprogram.exe', stdin=subprocess.PIPE,  stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True)
       outputs = myprogram.communicate(input=inputs)[0]
       myout.write(str(outputs))
       myout.close()
    Neither one of these writes anything to output, however when I run my batch command, it works like a charm. :/ Please tell me I'm missing something obvious.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,854
    Rep Power
    481
    Code:
    import subprocess
    with open('p.py','r') as myinput:
        with open('nivel.navel','w') as myoutput:
            p = subprocess.Popen('cat', stdin=myinput, stdout=myoutput, shell=True)
            p.wait()
    In unix, the cat program copies input to output. I'm using a sufficiently unix system, and the program works.

    What have I done differently from you????

    I opened my output file with write access.

    open('nivel.navel','w')


    Look, why don't you just
    Code:
    p = subprocess.Popen(
        'myprogram <myinput.in >myoutput.out',
        shell=True)
    
    p.wait()
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    12
    Rep Power
    0
    Thanks for the response! Turns out it was a problem with the absolute path not being a raw string and '\n' being in the path.
    >.<

IMN logo majestic logo threadwatch logo seochat tools logo