mercredi 15 juin 2016

Python 2.6 : piping bash commands containing python variables(inside python script)

I want to run the below bash command from my python script:

stat --printf='%U%G%a' /tmp/file1.csv &&md5sum /tmp/file1.csv |awk '{print $1}'

I have done it using subprocess.Popen as below:

Command=subprocess.Popen(["stat --printf='%U%G%a' file1.csv &&md5sum file1.csv|awk '{print $1}'"],stdout=subprocess.PIPE,shell=True)

But instead of hard coding the filename I need to pass a python variable. I tried

filevar="/tmp/file.csv"
Command=subprocess.Popen(["stat --printf='%U%G%a' filevar &&md5sum filevar|awk '{print $1}'"],stdout=subprocess.PIPE,shell=True)

But the above code is not working.

I have been through all the answers related to How to pass a python variable to subprocess

The best answer I got till now is piping python variable value to bash script (inside python script)

Based on this I tried:

Command=subprocess.Popen(["stat","--printf='%U%G%a'",filevar],stdout=subprocess.PIPE)

Which works great. But when I try to include more commands like md5sum it throws error.

Command=subprocess.Popen(["stat","--printf='%U%G%a'",filevar,"&&","md5sum",filevar],stdout=subprocess.PIPE)

Please suggest how this could be done.

Aucun commentaire:

Enregistrer un commentaire