python调用popen.communicate通信没有输出

2024-06-08 21:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类函数声明为

    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)

像这样打电话

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

但我看不到输出,也不知道为什么

非常感谢您的帮助


Tags: 函数self声明defrootfilenameoutprocess
2条回答

要检索shell命令的输出,建议使用subprocess.check_outputshlex.split配合使用。你知道吗

例如:

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

也就是说,基于当前的问题标题,Rakesh是正确的。你知道吗

读取文件内容

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

如果需要使用子流程模块:

import subprocess

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

catFunc()

相关问题 更多 >