简体   繁体   中英

How to run multiple linux commands with variables from python

I am trying to implement the below from python using subprocess but getting stuck:

Within a python script I would like to do the below and echo to linux.

varname = "namegoeshere" 

varvalue = "12345"

echo "varname varvalue date +%s" | nc 127.0.0.1 2003

I expect that everything after the echo is run on the linux command prompt.

This is what I get

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

If you are using Python then you can try to use the subprocess.Popen module. A simple example would be:

from subprocess import Popen, PIPE

process = Popen(['cat', '/tmp/file.txt'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

If you just want to get the output of shell command in python, try the following code:

import os
output = os.popen('ls').read() 
print(output)

# this will print the output of `ls` command.

But there is many many more way to do this(like use subprocess), see this question .

Here is the document of subprocess and os module.

I found my question had been answered another way using the below link.

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()

Thanks for everyone's help

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