When I write some file with .py extension and containing the following code:
import subprocess, platform
cmd = "echo Hi"
subprocess.call(cmd, shell = True)
it will return "Hi" when I double-click the file in Windows or when I write a .bat file which makes Python execute the script.
However, what I actually want to do is to shut down the computer (by executing the Python script from a batch file).
To this end, I wrote the following code:
import subprocess, platform
cmd = "shutdown /s /t 1" if platform.system() == "Windows" \
else "systemctl poweroff"
subprocess.call(cmd, shell = True)
However, this will start to endlessly run the script without shutting down the computer. I.e., double-clicking the .py file opens a prompt which is continuously populated with the line C:\Users\... py myscript.py
.
If I open a command prompt and enter
> py
> import subprocess
> subprocess.call("shutdown /s /t 1")
the computer is shut down as expected.
So, how is this different from executing the script? Is this some security issue? And how can I get this to work?
I also tried os.system()
, as well as entering the subprocess call as a list (setting cmd = ["shutdown", "-s", "-t", "1"]
). All behaved similarly: The code works when executed from a Python prompt but it does not when I run Python from a batch file or by double-click. In those instances, the call to echo
, however, does work.