我正在尝试使用子进程从python实现以下内容但是卡住了:
在python脚本中,我想执行以下操作并回显到linux。
varname = "namegoeshere"
varvalue = "12345"
echo "varname varvalue date +%s" | nc 127.0.0.1 2003
我希望echo之后的所有内容都在linux命令提示符下运行。
这就是我得到的
Traceback (most recent call last):
File "test.py", line 9, in <module>
subprocess.call("echo " , varname , varvalue, "date +%s ", "|" , "nc " , server , " " , port )
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 659, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer
答案 0 :(得分:3)
如果您使用的是Python,那么可以尝试使用subprocess.Popen模块。一个简单的例子是:
from subprocess import Popen, PIPE
process = Popen(['cat', '/tmp/file.txt'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
答案 1 :(得分:2)
如果您只想在python中获取shell命令的输出,请尝试以下代码:
import os
output = os.popen('ls').read()
print(output)
# this will print the output of `ls` command.
但是还有很多方法可以做到这一点(比如使用子流程),请参阅this question。
以下是subprocess和os模块的文档。
答案 2 :(得分:-1)
我发现我的问题已经使用以下链接以另一种方式回答。
http://coreygoldberg.blogspot.co.ke/2012/04/python-getting-data-into-graphite-code.html
import socket
import time
CARBON_SERVER = '0.0.0.0'
CARBON_PORT = 2003
message = str(varname) + " " + str(varvalue) + " " + '%d\n' % int(time.time())
print 'sending message:\n%s' % message
sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(message)
sock.close()
感谢大家的帮助