python - 执行命令并获取输出 [英] python - execute command and get output

查看:548
本文介绍了python - 执行命令并获取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个可以执行命令行命令并返回命令输出的服务器。



示例: p>

对于命令 - echo hello world,服务器将返回字符串hello world。



我试图使用 subprocess.call()函数,但它返回一个数字,而不是一个字符串。我有服务器准备好了,我只需要这个。



$ b

代码:

  type = struct.pack(B,2)#packing type 
data = subprocess.call(client_data,shell = True)
length = struct.pack(H,len(data))#packing lenght
client_soc.send(type + length + data)


解决方案

如何使用 subprocess.check_output ?从手册:
运行带参数的命令,并返回其输出的字节字符串



这将是类似于 = subprocess.check_output(client_data,shell = True)然后。



请参阅此手册页了解详情。


I need to build a server that can execute a command line command and send back the output of the command

Example:

for the command- echo hello world, the server will return the string "hello world".

I tried to use subprocess.call() function but it returns a number and not a string. I have the sever ready, i just need this this.

Code:

type=struct.pack("B",2) #packing type
data=subprocess.call(client_data, shell=True)
length=struct.pack("H",len(data)) #packing lenght
client_soc.send(type+length+data)

解决方案

How about using subprocess.check_output instead? From the manual: "Run command with arguments and return its output as a byte string."

It would be something like data = subprocess.check_output(client_data, shell=True) then.

See this man page for more information.

这篇关于python - 执行命令并获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆