How is a process named? - process

I have a program called xatelite, that is literally a script in /usr/local/bin/xatelite that has the following content.
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from xatelite import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
When I run this within a tmux instance, the pane takes the name python3.6*, because that is the process that is running. How do I make sure that the process is named xatelite. I want this to also be the case in htop and other programs that inspect processes.

You can start a new session with
tmux new -n windowname program
Within the tmux session you can change the name of the window with PREFIX + ,

Related

Argparser interactive

My question is pretty straight,
Is argaparse has an option to prompt missed arguments just via input?
script.py:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('mode', metavar='', help='Set count of likes', default=49)
parser.add_argument('-n', '--number', metavar='', help='Set count of likes', default=49, required=True)
parser.add_argument('-f', '--frequency', metavar='', help='Set chance to like/dislike', default=70)
# Running it via bash:
$ python script.py
# argparse automaticaly checking that missed argument "--number" and asking it via input built-in
>>> (argparse) Missed required argument "number", please specify it now, number:

stderr changes behavior of python's Popen when closing the script

I was using this script on python2 to launch an application and then immediately exit the python script without waiting for the child process to end. This was my code:
kwargs = {}
if platform.system() == 'Windows':
# from msdn [1]
CREATE_NEW_PROCESS_GROUP = 0x00000200 # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008 # 0x8 | 0x200 == 0x208
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
kwargs.update(stderr=subprocess.PIPE)
elif sys.version_info < (3, 2): # assume posix
kwargs.update(preexec_fn=os.setsid)
else: # Python 3.2+ and Unix
kwargs.update(start_new_session=True)
subprocess.Popen([APP], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,**kwargs)
It works OK on python 2.7, but it doesn't start the expected 'APP' on python 3.7 without changes.
In order to make it work in python3, I found two independent workarounds:
Change stderr to this: stderr=subprocess.DEVNULL
or
Add a time.sleep(0.1) call after the Popen (before closing the script).
I assume this is not actually related to python, but to some event that needs to happen after the process gets opened before the python script can safely exit?
Any hints? I'd really like to know why it happens. Right now I simply added the sleep call.
Thank you

How can I Make multiple asynchronous call to python cgi script

I have a CGI form which takes a CSV sheet and email and calls two individual python scripts which run in the background. These take about 15 minutes to execute. I want to make an asynchronous call to these scripts so that I can display some message and prevent apache timeout.
Here is my code
import os
import cgi, cgitb
import csv
import sys
import subprocess
import io
cgitb.enable()
form = cgi.FieldStorage()
filedata = form['file']
filecontent = filedata.file.read().splitlines()
email=form.getvalue('email_address')
email = str(email)
subprocess.Popen([sys.executable, 'giw.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)
subprocess.Popen([sys.executable, 'mailer.py', str(email)], shell=False,
stdin=None, stdout=None, stderr=None, close_fds=True)
This worked for me:-
Run background process in Python and do NOT wait
import subprocess
import sys
subprocess.Popen([sys.executable, 'giw.py', str(email)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);

Create Dialog Box in Blender using C or Python

How to make a dialog box (three options like quit/OK/Cancel) in blender and processing the text entered through python or in C. I'm unable to find any good tutorial on this. Any help....?
A quick and dirty way is to use zenity command (should be included by default in any python distribution). Try this short example script, it works in my Blender 2.69 on Ubuntu 14.04.
import bpy # bpy or bge does not matter
import subprocess as SP
# call an OS subprocess $ zenity --entry --text "some text"
# (this will ask OS to open a window with the dialog)
res=SP.Popen(['zenity','--entry','--text',
'please write some text'], stdout=SP.PIPE)
# get the user input string back
usertext=str(res.communicate()[0][:-1])
# adjust user input string
text=usertext[2:-1]
print("I got this text from the user: %s"%text)
See the zenity --help for more complex dialogs
blender doesn't offer things like dialogs.
Answers to This previous question on external modules may be helpful.
class DialogOperator(bpy.types.Operator)
bl_idname = "object.dialog_operator"
bl_label = "Save Before You QUIT!"
def execute(self, context):
message = " You didn't saved yet "
self.report({'INFO'}, message)
print(message)
return {'FINISHED'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
class DialogPanel(bpy.types.Panel)
bl_label = "Dialog"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
def draw(self, context):
self.layout.operator("object.dialog_operator")
But this is only for creating a dialog window. after this have to insert buttons in this code.If anyone known this try to post the answer. At the same time I'm also trying to sort out this.

Is it possible to ack nagios alerts from the terminal?

I have nagios alerts set up to come through jabber with an http link to ack.
Is is possible there is a script I can run from a terminal on a remote workstation that takes the hostname as a parameter and acks the alert?
./ack hostname
The benefit, while seemingly mundane, is threefold. First, take http load off nagios. Secondly, nagios http pages can take up to 10-20 seconds to load, so I want to save time there. Thirdly, avoiding slower use of mouse + web interface + firefox/other annoyingly slow browser.
Ideally, I would like a script bound to a keyboard shortcut that simply acks the most recent alert. Finally, I want to take the inputs from a joystick, buttons and whatnot, and connect one to a big red button bound to the script so I can just ack the most recent nagios alert by hitting the button lol. (It would be rad too if the button had a screen on the enclosure that showed the text of the alert getting acked lol)
Make fun of me all you want, but this is actually something that would be useful to me. If I can save five seconds per alert, and I get 200 alerts per day I need to ack, that's saving me 15 minutes a day. And isn't the whole point of the sysadmin to automate what can be automated?
Thanks!
Yes, it's possible to ack nagios by parsing /var/lib/nagios3/retention.dat file.
See :
#!/usr/bin/env python
# -*- coding: utf8 -*-
# vim:ts=4:sw=4
import sys
file = "/var/lib/nagios3/retention.dat"
try:
sys.argv[1]
except:
print("Usage:\n"+sys.argv[0]+" <HOST>\n")
sys.exit(1)
f = open(file, "r")
line = f.readline()
c=0
name = {}
state = {}
host = {}
while line:
if "service_description=" in line:
name[c] = line.split("=", 2)[1]
elif "current_state=" in line:
state[c] = line.split("=", 2)[1]
elif "host_name=" in line:
host[c] = line.split("=", 2)[1]
elif "}" in line:
c+=1
line = f.readline()
for i in name:
num = int(state[i])
if num > 0 and sys.argv[1] == host[i].strip():
print(name[i].strip("\n"))
You simply have to put the host as parameter, and the script will displays the broken services.