Search code examples
pythonbashpopen

Echo Python variable in shell command


I have the following Python function which interacts with Bash.

How do I get it to echo out the value of file1 and file2 using call or Popen? So something along the lines of echo $file1 file2 but executed from Python onto a Bash terminal? My script currently compares the content of both files, but I want to make sure that the correct files are being compared.

def compareFiles(file1, file2)  
     result = Popen("diff " + file1 + " " + file2 + " | wc -l", shell=True, stdout=PIPE)
     if int(result) > 0:
         raise Exception("Error found")
     else:
         return 0

So I know I have to do something like call("echo file1 file2", shell=True, stdout=PIPE), but it doesn't work. What is the correct format?


Solution

  • You have the file paths right there as arguments to the function: file1 and file2.

    Open and read them in Python. There's no reason to shell out if you don't have to.

    with open(file1, "rb") as f:
        file1_data = f.read()
    
    with open(file2, "rb") as f:
        file2_data = f.read()
    
    print(file1_data)
    print(file2_data)