running uwsgi in supervisor goes wrong but goes well in command line - uwsgi

I have some problem running uwsgi under supervisord.
The main problem is that with command line, I run uwsgi --ini /home/satori/mysite/src/mysite_uwsgi.ini, everythings goes well, but when I run it under supervisorctl, the server returned 500 when I upload a file with non-ascii character name.
But it won't happen if I run in the command line, the file is correctly uploaded.
I think the problen is related to my supervisor config file, maybe some environment issues. My config file is in /etc/supervisord.conf
This is my mysite_uwsgi.ini file, it's in /home/satori/mysite/src/mysite_uwsgi.ini
# mysite_uwsgi.ini file
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /home/satori/mysite/src
# Django's wsgi file
module = mysite.wsgi
# the virtualenv (full path)
#home = /home/ubuntu/mysite/bin
#plugins = python34
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = /home/satori/mysite/src/mysite.sock
# ... with appropriate permissions - may be needed
chmod-socket = 666
# clear environment on exit
vacuum = true
and this is the related settings in supervisord.conf
[program:mysite]
command=uwsgi --ini /home/satori/mysite/src/mysite_uwsgi.ini
autostart=true
autorestart=true
user=root
log_stderr=true
stdout_logfile=/var/log/mysite.log
And this is the 500 error:
UnicodeEncodeError at /upload/view/
'ascii' codec can't encode characters in position 37-38: ordinal not in range(128)
models.py
# encoding: utf-8
import os
from django.db import models
from django.conf import settings
def get_upload_path(instance, filename):
filename = ''.join([ch for ch in filename if ord(ch) < 128])
return os.path.join("user_%d" % instance.owner.id, filename)
class Picture(models.Model):
"""This is a small demo using just two fields. The slug field is really not
necessary, but makes the code simpler. ImageField depends on PIL or
pillow (where Pillow is easily installable in a virtualenv. If you have
problems installing pillow, use a more generic FileField instead.
"""
file = models.ImageField(upload_to=get_upload_path)
slug = models.SlugField(max_length=50, blank=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.file.name
#models.permalink
def get_absolute_url(self):
return ('upload-new', )
def save(self, *args, **kwargs):
self.slug = self.file.name
super(Picture, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""delete -- Remove to leave file."""
self.file.delete(False)
super(Picture, self).delete(*args, **kwargs)

You should add this to your uwsgi.ini file
env = PYTHONIOENCODING=UTF-8
Also, not sure if this is what you did, but I used str instead of unicode. I was using a plugin which required str, in that case you can write:
def __str__(self):
return YourModel.__unicode__(self)

Related

Why do I keep getting this error message in buildozer even tho I installed every single thing it needs?

I made a simple python app using kivy and when I wanted to convert it to apk using buildozer it kept giving me this error. I searched everywhere but couldn't find any solution. Do you guys have any idea ?
(stackoverflow is asking me to provide more details so don't mind this line. Below is the output I get when running the buildozer -v android debug command.)
root#DESKTOP-VQBOS27:/home/dtomper/environments/Tests/app test# buildozer -v android debug
# Check configuration tokens
Buildozer is running as root!
This is not recommended, and may lead to problems later.
Are you sure you want to continue [y/n]? y
# Ensure build layout
# Check configuration tokens
# Preparing build
# Check requirements for android
# Run 'dpkg --version'
# Cwd None
Debian 'dpkg' package management program version 1.19.7 (amd64).
This is free software; see the GNU General Public License version 2 or
later for copying conditions. There is NO warranty.
# Search for Git (git)
# -> found at /usr/bin/git
# Search for Cython (cython)
# -> found at /usr/bin/cython
# Search for Java compiler (javac)
# -> found at /usr/lib/jvm/java-8-openjdk-amd64/bin/javac
# Search for Java keytool (keytool)
# -> found at /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/keytool
# Install platform
# Run 'git config --get remote.origin.url'
# Cwd /home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android
https://github.com/kivy/python-for-android.git
# Run 'git branch -vv'
# Cwd /home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android
* master 5a94d074 [origin/master] Merge pull request #2244 from Chronolife-team/native_services_upstream
# Run '/usr/bin/python3 -m pip install -q --user \'appdirs\' \'colorama>=0.3.3\' \'jinja2\' \'six\' \'enum34; python_version<"3.4"\' \'sh>=1.10; sys_platform!="nt"\' \'pep517<0.7.0"\' \'toml\''
# Cwd None
# Apache ANT found at /root/.buildozer/android/platform/apache-ant-1.9.4
# Android SDK found at /root/.buildozer/android/platform/android-sdk
# Recommended android's NDK version by p4a is: 19c
# Android NDK found at /root/.buildozer/android/platform/android-ndk-r19c
# Check application requirements
# Compile platform
# Run '/usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=python3,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/dtomper/environments/Tests/app test/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21 --ignore-setup-py'
# Cwd /home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android
/home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py:84: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
Traceback (most recent call last):
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1260, in <module>
main()
File "/home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
ToolchainCL()
File "/home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 694, in __init__
self.ctx.setup_dirs(self.storage_dir)
File "/home/dtomper/environments/Tests/app test/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 173, in setup_dirs
raise ValueError('storage dir path cannot contain spaces, please '
ValueError: storage dir path cannot contain spaces, please specify a path with --storage-dir
# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=python3,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/dtomper/environments/Tests/app test/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21 --ignore-setup-py
# ENVIRONMENT:
# SHELL = '/bin/bash'
# SUDO_GID = '1000'
# SUDO_COMMAND = '/usr/bin/bash'
# SUDO_USER = 'dtomper'
# PWD = '/home/dtomper/environments/Tests/app test'
# LOGNAME = 'root'
# HOME = '/root'
# LANG = 'C.UTF-8'
# LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:'
# LESSCLOSE = '/usr/bin/lesspipe %s %s'
# TERM = 'xterm-256color'
# LESSOPEN = '| /usr/bin/lesspipe %s'
# USER = 'root'
# SHLVL = '1'
# PS1 = '\\[\\e]0;\\u#\\h: \\w\\a\\]${debian_chroot:+($debian_chroot)}\\u#\\h:\\w\\$ '
# PATH = '/root/.buildozer/android/platform/apache-ant-1.9.4/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin'
# SUDO_UID = '1000'
# MAIL = '/var/mail/root'
# _ = '/usr/local/bin/buildozer'
# OLDPWD = '/home/dtomper/environments/Tests'
# PACKAGES_PATH = '/root/.buildozer/android/packages'
# ANDROIDSDK = '/root/.buildozer/android/platform/android-sdk'
# ANDROIDNDK = '/root/.buildozer/android/platform/android-ndk-r19c'
# ANDROIDAPI = '27'
# ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
ValueError: storage dir path cannot contain spaces, please specify a path with --storage-dir
As it says, try using a directory without spaces in its name.

How to install systemd service on nixos

If I do this:
#!/usr/bin/env bash
set -e;
cd "$(dirname "$BASH_SOURCE")"
ln -sf "$(pwd)/interos-es-mdb.service" '/etc/systemd/system/interos-es-mdb.service'
systemctl enable interos-es-mdb.service
systemctl start interos-es-mdb.service
then I get this error:
ln: failed to create symbolic link '/etc/systemd/system/interos-es-mdb.service': Read-only file system
anyone know the right way to install a service on nixos machine? (I am the root user)...here is the service for reference:
[Unit]
Description=Interos MongoDB+ES log capture
After=network.target
[Service]
Environment=interos_emit_only_json=yes
EnvironmentFile=/root/interos/env/es-service.env
StartLimitIntervalSec=0
Type=simple
Restart=always
RestartSec=1
ExecStart=/root/interos/repos/elastic-search-app/syslog-exec.sh
[Install]
WantedBy=multi-user.target
update:
perhaps what I am looking for is "per-user" service, not something run as root etcetera.
The reason its broken
NixOS is a declarative operating system. This means that directories like /etc live inside the read-only /nix/store directory. Only the nix-daemon is allowed to mount the nix-store as writable. Therefore, you must create a systemd.services.<yourservice> entry in your configuration.nix to interact with the underlying system; alternatively you can patch nixpkgs directly and point your configuration to your fork.
All running services not declared explicitly by the user can be assumed to live inside nixpkgs/nixos/modules.
Fix
configuration.nix:
{
systemd.services.foo = {
enable = true;
description = "bar";
unitConfig = {
Type = "simple";
# ...
};
serviceConfig = {
ExecStart = "${foo}/bin/foo";
# ...
};
wantedBy = [ "multi-user.target" ];
# ...
};
}
user services
almost identical except they begin with systemd.user.services. In addition, user home directories are not managed declartively, so you can also place a regular systemd unit file under $XDG_CONFIG_DIR/systemd as usual.
relevant:
Full list of valid attributes for systemd.services.<name>, From: NixOS Manual
Module basics, From: Wiki
An appropriate entry in your /etc/nixos/configuration.nix might look like:
let
# assumes you build a derivation for your software and put it in
# /etc/nixos/pkgs/interosEsMdb/default.nix
interosEsMdb = import ./pkgs/interosEsMdb {};
in config.systemd.services.interosEsMdb = {
description = "Interos MongoDB+ES log capture";
after = ["network.target"];
wantedBy = ["multi-user.target"];
serviceConfig = {
# change this to refer to your actual derivation
ExecStart = "${interosEsMdb}/bin/syslog-exec.sh";
EnvironmentFile = "${interosEsMdb}/lib/es-service.env";
Restart = "always";
RestartSec = 1;
}
}
...assuming you actually build a derivation for interosEsMdb (which is the only sane and proper way to package software on NixOS).

Rails app does not read env variables in .bashrc

I have saved some ENV's in ~/.bashrc, I close and reopened the file and they are there for sure.
.bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
. /etc/apache2/envvars
# If not running interactively, don't do anything else
[ -z "$PS1" ] && return
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
PS1='\[\033[01;32m\]${C9_USER}\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1 " (%s)") $ '
# If this is an xterm set the title to user#host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u#\h: \w\a\]$PS1"
;;
*)
;;
esac
export rvm_silence_path_mismatch_check_flag=1
export TWILIO_SID="AXXXXX81b7eb5aXXXXeXXX6c9bfecX6X"
export TWILIO_TOKEN="XXX87XXXXXXe650ff2XXXXfXXXXX8X2"
export TWILIO_PHONE_NUMBER="+147043XXXX"
Yet when I tell my rails app to use them, for example use ENV["TWILIO_SID"] in my controller, it does not know them. I tried echoing them out in bash, it's just an empty line, in HTML, also empty line.
I am using c9 cloud IDE, and there is an option to manually enter ENV into the Rails shell, and when I do that, everything works fine. but my assignment asks for bashrc file... why are neither bash nor rails terminal reading my .bashrc? any help?
PS: the overall goal is to just set a UNIX env variable in my Rails app. I cannot use figaro.
PS2: Here is the code in controller where I'm using the variables. When I hard code them, everything works fine, so I know there is something going on with the env variables.
require 'twilio-ruby'
def index
end
class TexterController < ApplicationController
def index
end
def text
#number = params[:number]
#message = params[:message]
twilio_sid = ENV["TWILIO_SID"]
twilio_token = ENV["TWILIO_TOKEN"]
twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]
#client = Twilio::REST::Client.new(twilio_sid, twilio_token)
#message = #client.messages.create(
to: #number,
from: twilio_phone_number,
body: #message
)
render "pages/text.html.erb"
end
end
And here is the reasons why:
To change the environmental variable "permanently" you'll need to consider at least these situations:
Login/Non-login shell
Interactive/Non-interactive shell
Bash as login shell will load /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile in the order
Bash as non-login interactive shell will load ~/.bashrc
Bash as non-login non-interactive shell will load the configuration specified in environment variable $BASH_ENV
Source: how to permanently set environmental variables
Found it.
Turns out for some reason, even when I source .bashrc, the env variables are not read, but when I added them to .profile they are read and everything works fine.
Even tried adding them to .bashrc and then source ~/.bashrc to .profile, but still wouldn't work.

dataflow failed to set up worker

Tested my pipeline on DirectRunner and everything's working good.
Now I want to run it on DataflowRunner. It doesn't work. It fails even before enter my pipeline code, and I'm totally overwhelmed by the logs in stackdriver - just don't understand what they mean and really don't have any clue on what's wrong.
execution graph looks loaded fine
worker pool starts and 1 worker is trying to run through the setup process, however looks never success
some logs that I guess might provide useful information for debugging:
AttributeError:'module' object has no attribute 'NativeSource'
/usr/bin/python failed with exit status 1
Back-off 20s restarting failed container=python pod=dataflow-fiona-backlog-clean-test2-06140817-1629-harness-3nxh_default(50a3915d6501a3ec74d6d385f70c8353)
checking backoff for container "python" in pod "dataflow-fiona-backlog-clean-test2-06140817-1629-harness-3nxh"
INFO SSH key is not a complete entry: .....
How should I tackle this problem?
Edit:
my setup.py here if it helps: (copyed from [here], only modifiedREQUIRED_PACKAGES
and setuptools.setup section)
from distutils.command.build import build as _build
import subprocess
import setuptools
# This class handles the pip install mechanism.
class build(_build): # pylint: disable=invalid-name
"""A build command class that will be invoked during package install.
The package built using the current setup.py will be staged and later
installed in the worker using `pip install package'. This class will be
instantiated during install for this specific scenario and will trigger
running the custom commands specified.
"""
sub_commands = _build.sub_commands + [('CustomCommands', None)]
# Some custom command to run during setup. The command is not essential for this
# workflow. It is used here as an example. Each command will spawn a child
# process. Typically, these commands will include steps to install non-Python
# packages. For instance, to install a C++-based library libjpeg62 the following
# two commands will have to be added:
#
# ['apt-get', 'update'],
# ['apt-get', '--assume-yes', install', 'libjpeg62'],
#
# First, note that there is no need to use the sudo command because the setup
# script runs with appropriate access.
# Second, if apt-get tool is used then the first command needs to be 'apt-get
# update' so the tool refreshes itself and initializes links to download
# repositories. Without this initial step the other apt-get install commands
# will fail with package not found errors. Note also --assume-yes option which
# shortcuts the interactive confirmation.
#
# The output of custom commands (including failures) will be logged in the
# worker-startup log.
CUSTOM_COMMANDS = [
['echo', 'Custom command worked!']]
class CustomCommands(setuptools.Command):
"""A setuptools Command class able to run arbitrary commands."""
def initialize_options(self):
pass
def finalize_options(self):
pass
def RunCustomCommand(self, command_list):
print 'Running command: %s' % command_list
p = subprocess.Popen(
command_list,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Can use communicate(input='y\n'.encode()) if the command run requires
# some confirmation.
stdout_data, _ = p.communicate()
print 'Command output: %s' % stdout_data
if p.returncode != 0:
raise RuntimeError(
'Command %s failed: exit code: %s' % (command_list, p.returncode))
def run(self):
for command in CUSTOM_COMMANDS:
self.RunCustomCommand(command)
# Configure the required packages and scripts to install.
# Note that the Python Dataflow containers come with numpy already installed
# so this dependency will not trigger anything to be installed unless a version
# restriction is specified.
REQUIRED_PACKAGES = ['apache-beam==2.0.0',
'datalab==1.0.1',
'google-cloud==0.19.0',
'google-cloud-bigquery==0.22.1',
'google-cloud-core==0.22.1',
'google-cloud-dataflow==0.6.0',
'pandas==0.20.2']
setuptools.setup(
name='geotab-backlog-dataflow',
version='0.0.1',
install_requires=REQUIRED_PACKAGES,
packages=setuptools.find_packages(),
)
worker-startup log: and it ended at the following exception
I /usr/bin/python failed with exit status 1
I /usr/bin/python failed with exit status 1
I AttributeError: 'module' object has no attribute 'NativeSource'
I class ConcatSource(iobase.NativeSource):
I File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/concat_reader.py", line 26, in <module>
I from dataflow_worker import concat_reader
I File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/maptask.py", line 31, in <module>
I from dataflow_worker import maptask
I File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 26, in <module>
I from dataflow_worker import executor
I File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 63, in <module>
I from dataflow_worker import batchworker
I File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/start.py", line 26, in <module>
I exec code in run_globals
I File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
I "__main__", fname, loader, pkg_name)
I File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
I AttributeError: 'module' object has no attribute 'NativeSource'
I class ConcatSource(iobase.NativeSource):
You seem to be using incompatible requirements in your REQUIRED_PACKAGES directive, i.e. you specify "apache-beam==2.0.0" and "google-cloud-dataflow==0.6.0", which conflict with each other. Can you try removing / uninstalling the "apache-beam" package and install / include the "google-cloud-dataflow==2.0.0" package instead?

Capture output of shell command, line by line, into an array

I want to capture the total number of rubocop offenses to determine whether my codebase is getting better or worse. I have almost no experience with ruby scripting.
This is my script so far:
#!/usr/bin/env ruby
#script/code_coverage
var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`
puts var
So I ./rails-app/script/code_coverage and my terminal displays
...
--
6844 Total
When I var.inspect I get a long string. I want to either read the output of rubocop ../ -f ... line by line (preferred) or capture each line of output into an array.
I would like to be able to do something like this:
var.each |line| do
if line.contains('total')
...
total = ...
end
Is this possible? I guess this would be similar to writing the output to a file and and then reading the file in line by line.
If you want to keep it simple, you can simply split your var string.
var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`.split("\n")
Then you can iterate on var like you wanted to.
use open3 library of ruby. Open3 grants you access to stdin, stdout, stderr and a thread to wait the child process when running another program. You can specify various attributes, redirections, current directory, etc., of the program as Process.spawn.
http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html
require 'open3'
# Run lynx on this file.
cmd = "lynx -crawl -dump /data/feed/#{file_name}.html > /data/feed/#{file_name}"
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
cmdout = stdout.read
$logger.debug "stdout is:" + stdout.read
$logger.debug "stderr is:" + stderr.read
end

Resources