So I have designed a layout in Rainmeter which serves as a GUI for my Voice Assistant program. Now, I want to integrate the running of Rainmeter with Python. For example, if an user already has a Rainmeter layout loaded in his/her system, then running my script will automatically override his/her layout and activate my Layout unless he/she manually changes it back to his/her own layout. This process would continue whenever my script is run. It basically goes like this: The user runs the script, it checks whether any other skin is loaded or not (Assuming that Rainmeter is installed on the system). If any other skin is loaded, it overrides the skin with my one else it bypasses the override function and directly loads my skin.
I have no idea on how to achieve this thing. I have successfully written the lines to start and exit rainmeter with python but I don't know anything about how to load the layouts! Please help!
Here is the script I have written to start and exit Rainmeter:
import os
trigger = input()
if trigger == "y":
try:
os.startfile("C:\Program Files\Rainmeter\Rainmeter.exe")
print("Rainmeter started successfully")
except:
print("There was an error")
trigger = input()
if trigger == "exit":
try:
os.system("taskkill /f /im Rainmeter.exe")
print("Rainmeter closed successfully")
except:
print("There was an error")
You can use the following code to load a Rainmeter Layout:
import subprocess
subprocess.call(["C:\Program Files\Rainmeter\Rainmeter.exe", "!LoadLayout", "abcd"])
Here we are using rainmeter bangs to load the layout. Change abcd with name of your layout.
Related
Im trying to lock the volume of the sonos using SoCo in a webapp. I need to run a separate script to do this. So when the user presses the lock button it runs a loop constantly setting the volume to the value until the program gets called or toggled stopping it.
I need this done in a different script as if its in the main code i'm unable to get any user input to unlock it.
#app.route("/lock")
def lock():
run(togglelock.py)
return "ok"
#togglelock.py
toggle("F","T")
sound1 = (sonos.volume)
if toggle == "T":
sonos1.volume = sound1
else:
break
As long as the other python file is in the same directory, you can simply import it when you want to run it.
def lock():
import togglelock
return "ok"
#do more stuff....
I have a python project called the "Remote Dongle Reader". There are about 200 machines that have a "Dongle" attached, and a corresponding .exe called "Dongle Manager". Running the Dongle Manager spits out a "Scan" .txt file with information from the dongle.
I am trying to write a script, which runs from a central location, which has administrative domain access to the entire network. It will read a list of hostnames, go through each one, and bring back all the files. Once it brings back all the files, it will compile to a csv.
I have it working on my Lab/Test servers, but in production systems, it does nto work. I am wondering if this is some sort of login issue since people may be actively using the system. THe process needs to launch silently, and do everything int he background. However since I am connecting to the administrator user, I wonder if there is a clash.
I am not sure what's going on other than tge application works up until the point I expect the file to be there. The "Dongle Manager" process starts, but it doesnt appear to be spitting the scan out on any machine not logged in as administrator (the account I am running off of).
Below is the snippet of the WMI section of the code. This was a very quick script so I apoliogize for any non pythonic statements.
c = wmi.WMI(ip, user=username, password=password)
process_startup = c.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
cmd = r'C:\Program Files\Avid\Utilities\DongleManager\DongleManager.exe'
process_id, result = c.Win32_Process.Create(CommandLine=cmd,
ProcessStartupInformation=process_startup)
if result == 0:
print("Process started successfully: %d" % process_id)
else:
print("Problem creating process: %d" % result)
while not os.path.exists(("A:/"+scan_folder)):
time.sleep(1)
counter += 1
if counter > 20:
failed.append(hostname)
print("A:/"+scan_folder+"does not exist")
return
time.sleep(4)
scan_list = os.listdir("A:/"+scan_folder)
scan_list.sort(key=lambda x: os.stat(os.path.join("A:/"+scan_folder, x)).st_mtime, reverse=True)
if scan_list is []:
failed.append(hostname)
return
recursive_overwrite("A:/"+scan_folder+"/"+scan_list[0],
"C:\\AvidTemp\\Dongles\\"+hostname+".txt")
Assuming I get a connection (computer on), it usually fails at the point where it either waits for teh folder to be created, or expects something in the list of scan_folder... either way, something is stopping the scan from being created, even though the process is starting
Edit, I am mounting as A:/ elsewhere in the code
The problem is that you've requested to show the application window but there is no logged on desktop to display it. WMI examples frequently use SW_SHOWWINDOW but that's usually the wrong choice because with WMI you are typically trying to run something in the background. In that case, SW_HIDE (or nothing) is the better choice.
I have got a GUI aplication which includes five python scripts.
I have already found an error in the IO data, and then I'd like to include a escape condition to quit the python script and show a QT message but stay the GUI application.
one of the scripts
if len(Numero_Unidades) != 1:
quit()
else:
pass
block
but it quits python
and I want to stay in the GUI application, maintaining the main window open.
if self.ui.radioButton3.isChecked()== True:
myscript.myscript()
QtGui.QMessageBox.information(self,'message')
How can I do that?
You can start another python process to launch your script
By using os.system("script.py")
Assuming that the quit() function is the built-in quit, you can monkey-patch it and raise an error instead of quitting the whole appliaction:
import myscript
import __builtin__
def myquit():
raise RuntimeError('script quit!')
__builtin__.quit = myquit
try:
myscript.myscript()
except RuntimeError as exception:
print(exception)
else:
print('keep calm and carry on')
I have a script runReports.py that is executed every night. Suppose for some reason the script takes too long to execute, I want to be able to stop it from terminal by issuing a command like ./runReports.py stop.
I tried to implement this by having the script to create a temporary file when the stop command is issued.
The script checks for existence of this file before running each report.
If the file is there the script stops executing, else it continues.
But I am not able to find a way to make the issuer of the stop command aware that the script has stopped successfully. Something along the following lines:
$ ./runReports.py stop
Stopping runReports...
runReports.py stopped successfully.
How to achieve this?
For example if your script runs in loop, you can catch signal http://en.wikipedia.org/wiki/Unix_signal and terminate process:
import signal
class SimpleReport(BaseReport):
def __init__(self):
...
is_running = True
def _signal_handler(self, signum, frame):
is_running = False
def run(self):
signal.signal(signal.SIGUSR1, self._signal_handler) # set signal handler
...
while is_running:
print("Preparing report")
print("Exiting ...")
To terminate process just call kill -SIGUSR1 procId
You want to achieve inter process communication. You should first explore the different ways to do that : system V IPC (memory, very versatile, possibly baffling API), sockets (including unix domain sockets)(memory, more limited, clean API), file system (persistent on disk, almost architecture independent), and choose yours.
As you are asking about files, there are still two ways to communicate using files : either using file content (feature rich, harder to implement), or simply file presence. But the problem using files, is that is a program terminates because of an error, it may not be able to write its ended status on the disk.
IMHO, you should clearly define what are your requirements before choosing file system based communication (testing the end of a program is not really what it is best at) unless you also need architecture independence.
To directly answer your question, the only reliable way to know if a program has ended if you use file system communication is to browse the list of currently active processes, and the simplest way is IMHO to use ps -e in a subprocess.
Instead of having a temporary file, you could have a permanent file(config.txt) that has some tags in it and check if the tag 'running = True'.
To achieve this is quiet simple, if your code has a loop in it (I imagine it does), just make a function/method that branches a check condition on this file.
def continue_running():
with open("config.txt") as f:
for line in f:
tag, condition = line.split(" = ")
if tag == "running" and condition == "True":
return True
return False
In your script you will do this:
while True: # or your terminal condition
if continue_running():
# your regular code goes here
else:
break
So all you have to do to stop the loop in the script is change the 'running' to anything but "True".
I have written a script that will keep itself up to date by downloading the latest version from a website and overwriting the running script.
I am not sure what the best way to restart the script after it has been updated.
Any ideas?
I don't really want to have a separate update script.
oh and it has to work on both linux/windows too.
In Linux, or any other form of unix, os.execl and friends are a good choice for this -- you just need to re-exec sys.executable with the same parameters it was executed with last time (sys.argv, more or less) or any variant thereof if you need to inform your next incarnation that it's actually a restart. On Windows, os.spawnl (and friends) is about the best you can do (though it will transiently take more time and memory than os.execl and friends would during the transition).
The CherryPy project has code that restarts itself. Here's how they do it:
args = sys.argv[:]
self.log('Re-spawning %s' % ' '.join(args))
args.insert(0, sys.executable)
if sys.platform == 'win32':
args = ['"%s"' % arg for arg in args]
os.chdir(_startup_cwd)
os.execv(sys.executable, args)
I've used this technique in my own code, and it works great. (I didn't bother to do the argument-quoting step on windows above, but it's probably necessary if arguments could contain spaces or other special characters.)
I think the best solution whould be something like this:
Your normal program:
...
# ... part that downloaded newest files and put it into the "newest" folder
from subprocess import Popen
Popen("/home/code/reloader.py", shell=True) # start reloader
exit("exit for updating all files")
The update script: (e.g.: home/code/reloader.py)
from shutil import copy2, rmtree
from sys import exit
# maybie you could do this automatic:
copy2("/home/code/newest/file1.py", "/home/code/") # copy file
copy2("/home/code/newest/file2.py", "/home/code/")
copy2("/home/code/newest/file3.py", "/home/code/")
...
rmtree('/home/code/newest') # will delete the folder itself
Popen("/home/code/program.py", shell=True) # go back to your program
exit("exit to restart the true program")
I hope this will help you.
The cleanest solution is a separate update script!
Run your program inside it, report back (when exiting) that a new version is available. This allows your program to save all of its data, the updater to apply the update, and run the new version, which then loads the saved data and continues. To the user this can be completely transparent, as they just run the updater-shell which runs the real program.
To additionally support script calls with Python's "-m" parameter the following can be used (based on the Alex's answer; Windows version):
os.spawnl(os.P_WAIT, sys.executable, *([sys.executable] +
(sys.argv if __package__ is None else ["-m", __loader__.name] + sys.argv[1:])))
sys.exit()
Main File:
if __name__ == '__main__':
if os.path.isfile('__config.py'):
print 'Development'
push.update_server()
else:
e = update.check()
if not e: sys.exit()
Update File:
def check():
e = 1.....perform checks, if something needs updating, e=0;
if not e:
os.system("python main.pyw")
return e
Here's the logic:
Main program calls the update function
1) If the update function needs to update, than it updates and calls a new instances of "main"
Then the original instance of "main" exits.
2) If the update function does not need to update, then "main" continues to run
Wouldn't it just be easier to do something like
Very simple, no extra imports needed, and compatible with any OS depending on what you put in the os.system field
def restart_program():
print("Restarting Now...")
os.system('your program here')
You can use reload(module) to reload a module.