简体   繁体   中英

python call to popen.communicate gives no output

I have a class function declared as

    def catFunc(self,filename):
    print "catFunc",filename
    process = subprocess.Popen(['cat',/root/scratch.php], stdout=subprocess.PIPE, shell=True)
    out, err = process.communicate()
    print (out)
    print (err)

and called like this

fn = '/root/scratch.php'
self.catFunc(fn)

But I see no output and cannot figure out why

Any help greatly appreciated

To read content of file

def catFunc(self,filename):
    with open(filename) as f:
        s = f.read()
    return s

If you need to use the subprocess module:

import subprocess

def catFunc(filename):
    print "catFunc"
    task = subprocess.Popen(["cat", filename], stdout=subprocess.PIPE)
    print list(task.stdout)

catFunc()

To retrieve the output of a shell command it's recommend to use subprocess.check_output in cooperation with shlex.split .

For instance:

output = subprocess.check_output(shlex.split('cat "root/scratch.php"')

That said, Rakesh is correct based on the current question title.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM