Run a command inside a running python script - python

I think it's a very easy thing to do but im still searching for an answer.
I have a Python script running which looks like this:
Waiting for argument:_________
Is there an easy way how i can start the script and automatically put some arguments in it?

I really don't understand u but i think u want something like
import os, sys
#def some_other_functions
def cmd():
try:
com = raw_input('Waiting for argument:_________ ')
#Or u can pass values as sys.args
#like com = sys.argv[1]
while len(com) == 0:
com = raw_input('Waiting for argument:_________ ')
if len(com) != 0:
print os.system(com)
if str(com) == 'exit':
sys.exit()
print '\nContinuer executing other commands or write --exit to quite the program\n'
while True:
com = raw_input('Waiting for argument:_________ ')
if len(com) == 0:
print 'Entered nothing'
if str(com) == 'exit':
sys.exit()
else:
print os.system(com)
except Exception, e:
print str(e)
cmd()

Related

Python How to iterate through a list of functions

I have a bunch of functions that do x y and z, these functions get executed after an exception has occured. so my problem is that instead of writing the functions one by one i want to create a list of functions and a write a function to iterate through those functions in the list.
If you could show me an example that would be of great help.
here is what i have:
def call_va_funcs(self, stop):
self.disableZüruckVA()
while True:
try:
correct = urllib.request.urlopen("http://192.168.167.12", timeout=10).getcode()
print(correct, "192.168.100.2 is reachable: FAIL")
if correct == 200:
self.enableZüruckVA()
self.exitflag == True
break
except Exception:
print('Preflash')
if self.exitflag == True:
self.enableZüruckVA()
break
self.ping_all_va()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.run_rxtx()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.call_netzteil()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
As you can see here i am repeating the same process over and over again but with a different function. Can anyone help me figure out how to have a list and then just iterate through the bunch of functions.
Thank you
Let's say you have functionA(), functionB() and functionC().
You could put the names of the functions in a list like this:
f_list = [functionA, functionB, functionC]
You can then call these functions one after another:
while True:
# other code here...
try:
#... other code
except:
# ...other code
for func in f_list:
func()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
you could try smth like this
my_methods = []
my_methods.append('ping_all_va')
my_methods.append('run_rxtx')
my_methods.append('next_func')
for cmd in my_methods:
method = getattr(self, cmd)
method()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break

Pause and resume a running script in Python 3.42 in Windows

I'm new to Python and have been googling for a couple of days and read all I can find on this forum. Might be that I don't understand it all but I haven't found a solution to my problem yet. Ask for forgiveness already if there's an answer already to my problem, then I haven't understood it.
I want to make a Pause function for my program Tennismatch. The program will when it's being run print the score of a tennis match like this: "15-0, 15-15 etc ongoing till the match ends. It will print the score line by line.
I want the user to be able to pause after x number of balls, games, etc. So I don't know when the user wants to pause and after the user has paused I want the user to be able to resume the tennismatch where it was.
Have seen the time.sleep() but as I have understood it you must know when you want to pause to use this and it also ain't an indefinetie pause like I want. With input() it's the same.
Am going to make a GUI later on when the code is finished. Happy for anything that leads me to solving my problem.
I use Windows and Python 3.42 and run the program in Shell.
A piece of the code (haven't written it all yet, it's more of a general situation when something is being printed line after line for some time and want to be able do pause in the CIL:
#self.__points = [0,0]
def playGame(self):
if self.server == True: #self.server is either True or False when someone calls playGame()
server = self.player_1.get_win_serve() #self.player_1 = an object of a class Player():
else:
server = self.player_2.get_win_serve() #get_win_serve() method returns the probability to win his serv (1-0)
while (0 < self.__points[0] - self.__points[1] >= 2 or 0 < self.__points[1] - self.__points[0] >= 2) and (self.__points[1] >= 4 or self.__points[0] >= 4):
x = random.uniform(0,1)
if x > 0 and x < server:
self.__points[0] += 1
else:
self.__points[1] += 1
# print('The score, by calling a score() function that I haven't written yet')
For dealing with events in main loop you need to make a separated thread which capture input or any other event.
import sys
from sys import stdin
from time import sleep
from threading import Thread
from Queue import Queue, Empty
def do_something():
sleep(1)
print 42
def enqueue_output(queue):
while True:
# reading line from stdin and pushing to shared queue
input = stdin.readline()
print "got input ", input
queue.put(input)
queue = Queue()
t = Thread(target=enqueue_output, args=(queue,))
t.daemon = True
t.start()
pause = False
try:
while True:
try:
command = queue.get_nowait().strip()
print 'got from queue ', command
except Empty:
print "queue is empty"
command = None
if command:
if command == 'p':
pause = True
if command == 'u':
pause = False
if not pause:
print pause
do_something()
except KeyboardInterrupt:
sys.exit(0)
I came up with the following.
while True:
try:
## Keep doing something here
## your regular code
print '.',
except KeyboardInterrupt:
## write or call pause function which could be time.sleep()
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response.lower() == 'quit':
break
print 'Quitting...'
except KeyboardInterrupt:
print 'Resuming...'
continue
The Event loop might as well be the code I wrote with.
I don't see any user input so I assume that x emulates it. To pause the game if x < 0.1 and to unpause(/resume) it if x > 0.9, you could:
while your_condition(self.__points):
x = random.random()
if x < 0.1: # pause
self.pause()
elif x > 0.9: # resume
self.resume()
if self.is_paused:
continue # do nothing else only wait for input (`x`)
# assume your_condition() has no side-effects
# here's what the resumed version does:
print("...")
# change self.__points, etc
where pause(), resume(), is_paused() methods could be implemented as:
def __init__(self):
self.is_paused = False
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
as you can see the implementation is very simple.

Python - TCP Server

I'm new in python.
I've found a simple TCP Server's code and it works.
The problem is: i'm not able to make a if...elif...else works.
I think it's a mistake of value's type.
Here's my code (the program always do the else part):
while 1:
data = clientsocket.recv(1024)
tokens = data.split(' ',1)
command = tokens[0]
if not command:
break
else:
if command == 1:
try:
camera.start_preview()
time.sleep(10)
camera.stop_preview()
finally:
camera.close()
elif command == 2:
print "Something"
elif command == 3:
print "something else"
else:
print data
print tokens[0]
print command
clientsocket.close()
It give me the result of the last else which is :
2
2
2
Or the number I send. Thanks in advance for your responses !
command is a string, not an integer; you are comparing:
>>> '2' == 2
False
Instead, use:
...
tokens = data.split(' ', 1)
try:
command = int(tokens[0])
except ValueError:
break
if command == 1:
...

initialization problem in Python

The error is given at the end:
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.upnp.control_point.control_point import ControlPoint
def on_new_device(dev):
print 'Got new device:', dev.udn
print "Type 'list' to see the whole list"
if not dev:
return
def create_control_point():
c = ControlPoint()
print "hello"
c.subscribe('new_device_event', on_new_device)
print "c"
return c
def main():
print "Inside main"
c = create_control_point()
print "Inside create control point"
c.start()
reactor.add_after_stop_func(c.stop)
reactor.main()
def _search(c):
""" Start searching for devices of type upnp:rootdevice and repeat
search every 600 seconds (UPnP default)
"""
c.start_search(600, 'upnp:rootdevice')
def _stop(c):
""" Stop searching
"""
c.stop_search()
def _list_devices(c):
""" Lists the devices that are in network.
"""
k = 0
for d in c.get_devices().values():
print 'Device no.:', k
print 'UDN:', d.udn
print 'Name:', d.friendly_name
print 'Device type:', d.device_type
print 'Services:', d.services.keys() # Only print services name
print
k += 1
# Control the loop at _handle_cmds function
running_handle_cmds = True
commands = {
'search': _search,
'stop': _stop,
'list': _list_devices,
}
def _handle_cmds(c):
while running_handle_cmds:
try:
input = raw_input('>>> ').strip()
if len(input.split(" ")) > 0:
try:
if len(input.split(" ")) > 1:
commands[input.split(" ")[0]](c, input.split(" ")[1])
else:
commands[input.split(" ")[0]](c)
except KeyError, IndexError:
print 'Invalid command, try help'
except TypeError:
print 'Wrong usage, try help to see'
except KeyboardInterrupt, EOFError:
c.stop()
break
# Stops the main loop
reactor.main_quit()
if __name__ == '__main__':
print "hello"
main()
Error:
ankit#ubuntu:~/Desktop$ python controlpt.py
<brisa.core.reactors.glib2.GLib2Reactor object at 0x965bdcc>
hello
Inside main
After that I know understand, it is not initialising the control point. The Information about the libraries(Control point) is available at http://brisa.garage.maemo.org/apidoc/index.html
If this is anything like some other event-based libraries such as Twisted, you want to get the reactor's main running before you do much of anything else.
Drop the call to reactor.main in your main function. Then, instead of just calling main in your if at the bottom, do this:
if __name__ == "__main__":
run_async_function(main)
reactor.main()
See if things behave more like what you expect then.
(run_async_function is in the threaded_call module.)

Get process name by PID

This should be simple, but I'm just not seeing it.
If I have a process ID, how can I use that to grab info about the process such as the process name.
Under Linux, you can read proc filesystem. File /proc/<pid>/cmdline contains the commandline.
Try PSUtil -> https://github.com/giampaolo/psutil
Works fine on Windows and Unix, I recall.
For Windows
A Way to get all the pids of programs on your computer without downloading any modules:
import os
pids = []
a = os.popen("tasklist").readlines()
for x in a:
try:
pids.append(int(x[29:34]))
except:
pass
for each in pids:
print(each)
If you just wanted one program or all programs with the same name and you wanted to kill the process or something:
import os, sys, win32api
tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()
print(tasklistr)
def kill(process):
process_exists_forsure = False
gotpid = False
for examine in tasklistrl:
if process == examine[0:len(process)]:
process_exists_forsure = True
if process_exists_forsure:
print("That process exists.")
else:
print("That process does not exist.")
raw_input()
sys.exit()
for getpid in tasklistrl:
if process == getpid[0:len(process)]:
pid = int(getpid[29:34])
gotpid = True
try:
handle = win32api.OpenProcess(1, False, pid)
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
except win32api.error as err:
print(err)
raw_input()
sys.exit()
if not gotpid:
print("Could not get process pid.")
raw_input()
sys.exit()
raw_input()
sys.exit()
prompt = raw_input("Which process would you like to kill? ")
kill(prompt)
That was just a paste of my process kill program I could make it a whole lot better but it is okay.
Using psutil, here is the simplest code i can give you:
import psutil
# The PID ID of the process needed
pid_id = 1216
# Informations of the Process with the PID ID
process_pid = psutil.Process(pid_id)
print(process_pid)
# Gives You PID ID, name and started date
# psutil.Process(pid=1216, name='ATKOSD2.exe', started='21:38:05')
# Name of the process
process_name = process_pid.name()
Try this
def filter_non_printable(str):
ret=""
for c in str:
if ord(c) > 31 or ord(c) == 9:
ret += c
else:
ret += " "
return ret
#
# Get /proc/<cpu>/cmdline information
#
def pid_name(self, pid):
try:
with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile:
return filter_non_printable(pidfile.readline())
except Exception:
pass
return

Categories