It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Background
I need to create a python script that runs at start-up. The problem is that this script must be platform independent because it will be used on different operating systems. It needs to be an automatic set up because it will be run by the user and so I won't be able to set task schedulers up on each individual machine.
Questions
How to find out which OS a computer is running on in Python?
How to make a script run at startup (Linux, Mac OSX, Windows)
Question 1 is easy:
How to find out which OS a computer is running on in Python?
That's sys.platform:
if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
do_windows_stuff()
elif sys.platform.startswith('darwin'):
do_osx_stuff()
elif sys.platform.startswith('linux'):
do_linux_stuff()
else:
raise Exception("Nobody's written the stuff for {}, sorry".format(sys.platform))
The second part is also easy, but not in the way you wanted to hear:
How to make a script run at startup (Linux, Mac OSX, Windows)
You don't. Not from within the script. You use some kind of installer (or package postflight script, or whatever).
Adding things that run at startup requires root/admin rights. Your script (hopefully) is not running with such rights. Therefore, it can't do it. Yes, it's possible to elevate privileges in various ways, but that almost certainly isn't what you want to do inside a script that's going to end up running at startup.
So, how does your installer do it then?
OS X: You need to create a Launch Daemon, with an accompanying launchd plist. This is described in Creating Launch Daemons and Agents. You shouldn't be trying to do this if you haven't read that article, and you'll already know how if you have read that article, so there's not much else to say.
Windows: The official way to do this is explained in Run and RunOnce Registry Keys. Again, you shouldn't do this without reading this article, and after reading the article it's pretty obvious, except for two things: First, out of the four keys, it's the HKLM Run key. Second, in modern Windows, this doesn't actually run at startup, but at the first login after startup; if that's not acceptable, look into RunServices instead.
Linux: What's an installer? And were you expecting one way to do it for every distro family? This primer gives you most of the information you need, except for knowing exactly what you want to do on each distro. In general, if you just want your script to run once and quit, and there's an rc.local.d, and you just need to drop a link in there. Otherwise, you either need to create an rc.d script, install it to the right place, and run the right chkconfig command, or you need to edit rc.local to run your script. But the simplest thing is: just put English text in the INSTALL file telling people to do it. Eventually, when someone decides to make a DEB for Ubuntu or an RPM for Redhat or whatever, they'll do the right thing for their distro, and either submit a patch to you or maintain it separately.
Related
I have a bunch of python script that run on a scheduled basis in a windows 10 based system, sometimes after windows 10 automatic update, the OS will ask for a restart to finish the update and after some time it would restart automatically if not done manually which might mess with automated python script runs.
I am looking for a pythonic solution where I would query the OS if it needs a restart and upon getting the appropriate response I would trigger the appropriate solution
import necessary_libraries
isRestartRequired = check_if_restart_is_needed() // returns true or false
if isRestartRequired == True:
notifyUser()
Is this programmatically possible with python?
The following seems to work for me:
Install the PowerShell script Reboot pending:
Install-Module -Name PendingReboot
Check it works in Powershell:
Test-Pending Reboot
Call it from python using:
import subprocess
def restart_needed()->bool:
"""Uses Windows Powershell tool to figure out if a windows
reboot is pending. True indicates one is due."""
cmd:list[str]=["powershell","-Command","Test-PendingReboot"]
res:bytes=subprocess.run(cmd,capture_output=True)
output_text:str=res.stdout.decode("utf-8").strip()
restart:bool=output_text.endswith("True")
return restart
I personally don't think there is a dedicated library for that. I also don't think you should check that for updates individually, as that will likely require searching for the information about each and every update online (https://learn.microsoft.com/en-us/answers/questions/308547/how-to-know-if-a-windows-update-will-require-a-reb.html).
So you'll likely have to figure out a way how to determine whether Windows is going to reboot or not, and then manually perform that check (by running a system command or utility) in Python. Now your question sounds more like "Which mechanisms Windows use to reboot the machine during the update, and how to check whether any of them is invoked". Please note that there might be a bunch of such mechanisms, and they are most probably undocumented and may change in future. You can learn the basics on MS website, but they don't provide good amount of details there (https://learn.microsoft.com/en-us/windows/deployment/update/how-windows-update-works).
You can check the list of possible reboot status locations in How can I check for a pending reboot? (it looks quite promising), and implement these checks in Python afterwards using some function that allows you to check the output (Running shell command and capturing the output).
If you decide to use that approach, please capture a PC that requires a reboot and verify that one of the 4 sources mentioned in the answer indeed contains the reboot flag. I did it for my laptop yesterday - it was pending reboot, and some entries indeed contained that marker. Make sure you check that for your infrastructure as well.
P.S. If you have full control upon your entire infrastructure, you might look into PowerShell Gallery PendingReboot module mentioned in the referenced SO post (if it's installed on the machine, you can use just one command instead of four), or make yourself familiar with brilliant (and completely useless probably) opinion of MSDN guy https://devblogs.microsoft.com/oldnewthing/20151203-00/?p=92261 : In this specific case, the idea would be to change the design from “Install the update, and then postpone the reboot until a convenient time” to “Wait for a convenient time, then install the update and reboot immediately.”
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have to write a code for a group project and no one else knows anything about coding. I will have to make them install some libraries using pip for the code to learn which they might find pretty complicated. So i thought of writing a code for them which will install the libraries using the os module. But i dont know how to keep CMD open after it has installed since it closes as soon as the command is executed. PLEASE HELP!!
You can write a .bat file with a "Pause" at the end.
I would start by moving away from running python in the command line. There are some great package managers like Anaconda which also have nice IDEs such as spyder or VS code which can help with writing code if you are not beyond the write in notepad run in cmd stage yet.
You can then use anaconda prompt for package management operations. May i suggest looking into "pip install -r requirements.txt" still needs some user input but this is a great way of making sure someone has all the right packages. without them having to do pip install many times.
As for a direct solution to your problem, if you start cmd first, navigate to the directory via cmd and then from that terminal do "python file.py" you should be able to see output without the window closing. Though using an interactive IDE is much better. I'm on linux at the moment so may have skipped something.
This question already has an answer here:
Python script start on boot
(1 answer)
Closed 3 years ago.
I want to monitor a file in a specific location and check it for updates, which upon being updated launches certain actions via a python script.
Ideally, this program would always be running in the background and would automatically start with the computer so that the user does not have to mess with starting/stopping it.
I have researched the topic some and have found daemon and similar tools, but I do not understand how they work and they look far more complex then what I need. Also, many of the examples that I am looking at use Ubuntu OS and I will be using Windows.
Are there any python modules that exist to do this already or any direction you can point me to get started? I apologize if this question has been answered already, however I have not found it in my research.
I plan on editing this post to include code that performs this action, however I currently do not know where to start.
On Windows you could create a batch script and schedule it using the Windows Task Scheduler to run as a process on boot.
You can trigger the Python script to run inside the batch file,
python file.py
Alternatively, if you're using something like Anaconda as your environment manager; you could write a batch file to activate Anaconda using the activate.bat contained in the Scripts folder of your Anaconda installation path and then follow the usual calling steps.
Since the windows 10 creator update, you can enable developer mode to circumvent administrator privileges when creating a symlink. Now, I was able to create a symlink using mklink like this:
os.system('mklink %s %s' %(dst, src))
Hopefully it's obvious that dst is the destination symlink path, and src is the source file for the symlink. While it seems to work ok, it doesn't error if it fails which makes it a little more difficult to ensure each symlink is successful. I can check if the path exists after each symlink, but that's less efficient than a try/except clause. There's also what looks like a command shell window(?) that pops up and closes quickly every time - and that's really annoying when you're symlinking a lot of files...
So, I've been trying other options I've found on stack overflow like this one: How to create symlinks in windows using Python? Unfortunately, the CreateSymbolicLinkW command doesn't seem to work for me... I also found this: OS.symlink support in windows where it appears you need to adjust the group policy editor; however, it apparently still requires users in the administrator group to run the process as an administrator even if you explicitly set that user with symlink privileges.
With the windows 10 creator update, there's mention of a new dwflag in the CreateSymbolicLink api (SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) you can see the reference for that here: symlinks windows 10
Using the ctypes stuff is a bit over my head, so I'm wondering if anyone knows: Can I actually use that new dwflag? How do I use it? Will it work without running the process as administrator?
I use Autodesk Maya, so I'm stuck with python 2.7 options... I have not tried launching Maya as an administrator so I don't know if that will work, but it seems like a rather annoying hoop to jump through even if it does... I appreciate any assistance you can give
it doesn't error if it fails
os.system will return the exit status of the call. It does not raise an exception.
If you look at the docs for os.system, they recommend using the subprocess module. In fact, subprocess.check_call does what you describe (raise an exception on a non-zero exit status). Perhaps that would work better.
On the other hand, the command mklink will return a zero exit status even if the source does not exist (it will create a link to non-existent file and return 0). You might want to validate the actual link as you mentioned, depending on what errors you are trying to find.
As far as hiding the console window, see this.
os.symlink works out of the box since python 3.8 on windows, as long as Developer Mode is turned on.
Not sure whether this will help with Maya; they seem to have committed to Python 3 though.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 7 years ago.
Improve this question
I have installed Python 2.7 (Windwos 7). However, I am unable to load the GUI. I get no response when I try to open. I re-installed it but again the same problem. What might be the solution?
If you have python in the default installation path, try in the windows shell:
C:\Python27\pythonw C:\Python27\Lib\idlelib\idle.pyw
or change the path accordingly. This should work even if you have other conflicting pythons in your installation or paths are not set.
If idle comes, best solution is to modify idle.bat (in idlelib
folder) with the above explicit paths and create a desktop direct access to that new .bat.
If idle doesn't come, try
starting idle as administrator
starting idle after shutting down windows firewall
There can be lot of reasons and its difficult to diagnosis and recommend a solution without looking into the actual system and process. If you are really interested to resolve this I can suggest how you can debug these issues.
Download Process Monitor
Bring up process Monitor and filter all process except pythonw. PythonW is the process that runs when you start IDLE.
Now Start Monitoring in Process Monitor.
Bring up IDLE and wait until Process Monitor's Log becomes stable.
Now study the LOG to see what might have gone wrong.
If you need more help, just post the log here and we can try to see what is wrong with your system.
Just to simulate your problem, I renamed my idle.pyw so idle_1.pyw and tried to bring up IDLE. It failed without any message. I then brought up process Monitor, and filtered the pythonw process and tried to bring up IDLE again. I found a message in the log which was in coherence with the problem.
As you can see, I have highlighted the error which shows what the error yes. Try the process explorer and this would surely nail down the problem if nothing works for you :-)
Remember, just search for ThreadExit in the log, the Error should be just above the Operation. In case its difficult for your to figure out the problem, just post the screan shot near the ThreadExit, and we can help you out.
Update from the Image Provided
As you can see in the log, the FSECURE.DLL closed the thread abruptly. FSECURE (Antivirus/Firewall) didn't think this process to have legitimate rights to do some operation. If you need to know more details as to what operation was blocked you would get from Fsecure Log. In most cases as you have experienced, running as an Administrator would help the process gain the right to not being blocked by Fsecure.
I have no expericne with Fsecure, but most antivirus have a Whitelist entry where if you add a process would prevent it from blocking it.
I had the same problem after installing python 3.3.2 on my Windows 7 Professional x64.
During the setup I had to provide administrator privileges due to turned on UAC. Ever after when trying to start the IDLE nothing would happen - unless I started it as an administrator.
I checked the setup but couldn't make out an option for a non-admin install as described in http://bit.ly/15WBouF.
Inspired by the comment of Joaquin from above I deleted the entire folder named .idlerc located at my user directory. Et voila - IDLE runs as a charm!
Althought the root of the problem is still unknown to me this solved my issue.
I had similar problem, IDLE would stay silent and crash after couple more tries.
Then I tried to run the code from command line: >>python program.py
the command line said that I had problem with global variables. You have to declare a variable global in the beginning ot everyfunction before reaching it:
var1
def func():
global var1
...code..
##end of func()
IDLE would not show that problem. It's a handy tool, but sometimes leaves you speechless.
In keeping with simplicity, may I suggest removing Python 2.7, and download the stable version without known IDLE issues. That'd be Python 3.3.3. Click here --> Python 3.3.3 Python 3.4.1. is problematic.
Please select 'Start' > 'Computer' > Right Click on 'Computer' > Select 'Properties'.
Select 'Environmental Variables'.
Select 'New' or 'Edit' Variables. Path of the python.exe. C:\Python33.
Either Edit or input new Variables with naming conventions. This should remedy any issues with IDLE. However, regarding the GUI - may I suggest the following: 5) In the Command Prompt, type: cd C:\Python33. This should take care of it. Hope this helps.