kskp kskp - 2 months ago 7
Bash Question

Print file contents using cat in subprocess

I am using a subprocess call in python where I have to print a file contents using

cat
. The file name is a variable that I generate in the python code itself. This is my code:

pid = str(os.getpid())
tmp_file_path = "/tmp/" + pid + "/data_to_synnet"
synnet_output = subprocess.check_output(["cat echo '%s'"%tmp_file_path], shell=True)


The above code throws an error saying
cat: echo: No such file or directory
.

However, when I use only
subprocess.check_output(["echo '%s'"%tmp_file_path], shell=True)
, the variable name is printed correctly.

Also, I tried doing this (
cat echo $tmp_file_name
) in the command line and it works. Can someone please tell what is wrong?

Answer

The command you want is this:

"cat '%s'"%tmp_file_path

Just get rid of the "echo" word.

Alternatively,

 synnet_output = subprocess.check_output(["cat", tmp_file_path], shell=False)