3

I am trying to execute an echo command within a python script.

If I do it in the terminal, it looks like this:

echo -n -e '{"DATE": "Wednesday, May 04, 2016", "message": "ADIsss     ", "INDEX_CLOSING_VALUE": "4428.61"}'"\0" | nc -w0 127.0.0.1 12201

I tried using:


import subprocess
cmd = '''echo -n -e '{ "version": "1.1", "host": "example.org", "short_message": "A short message", "level": 5, "_some_info": "foo" }'"\0" | nc -w0 127.0.0.1 12201'''
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
print proc.communicate()[0],

i got a error :

Traceback (most recent call last):
  File "tet.py", line 3, in <module>
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

how can I solve this with subprocess in python

Pradeep Chandran
  • 327
  • 5
  • 11
  • 2
    have you tried making your `cmd` a list instead of a string? The [docs](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) show example of the command being a list. – SpaceMonkey55 May 08 '19 at 09:44

1 Answers1

1

Try using os module

import os
os.system("echo...........")

If you want to use variables here, you need to add here with out in quotation marks

for example

import os
string="This is test"
os.system("echo "+string+">> ~/Desktop/file.txt")

This code will append string "This is test" to the file.txt in Desktop location

KrisH Jodu
  • 104
  • 9