Open a Windows shortcut file `.lnk` with subprocess - python

I am fairly new to Python and have been trying to make a program that will open the "Minecraft launcher" for me.
Context
However, the new launcher .exe file is blocked as it is located in the windowsapp file which requires a lot of faffing about that I would rather avoid, so instead I was hoping to see if I could open the desktop shortcut instead to open the launcher directly?
Error
This code so far doesn't work as it gives me the error:
OSError: [WinError 193] %1 is not a valid Win32 application
Code
import time
import subprocess
subprocess.Popen('C:/Users/(my username)/Desktop/Minecraft Launcher.lnk')
I have tried subprocess.call however that doesn't seem to work either.

.lnk files are interpreted by the shell. So, enable the shell:
subprocess.call("C:\\Users\\My Username\\Desktop\\Minecraft Launcher.lnk", shell=True)
As a side note, the shell is one of the very few things in Windows that insists on backslashes.

Related

Python subprocess can't call "ssh"

I'm working on using the subprocess module to send shell commands from Python, specifically, ssh. Below is a barebones sample:
import subprocess
sp = subprocess.run(["ssh"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"stdout: {sp.stdout.decode()} \n\nstderr: {sp.stderr.decode()}")
This should return the ssh command help from stdout, and nothing from stderr. However, I get:
stdout:
stderr: 'ssh' is not recognized as an internal or external command,
operable program or batch file.
I've tried other commands, like echo and cd, and those work fine. I am also able to use ssh when manually typing the command into the shell, but it fails when I try to do it through subprocess. The directory C:\Windows\System32\OpenSSH does exist on my computer (and it contains ssh.exe), but for some strange reason I'm unable to cd to it using subprocess.
If it matters, subprocess is using the command prompt, cmd.exe, as it seems to be the default.
Any help is appreciated. Thanks!
-- Edits with tests from comments --
Using the absolute path C:/Windows/System32/OpenSSH/ssh.exe does not work, and gives The system cannot find the path specified via stderr. The OpenSSH folder doesn't seem to be visible to Python through subprocess
os.environ[PATH] contains both C:/Windows/System32/ and C:/Windows/System32/OpenSSH/
Running it with shell=False (either with the absolute path or just with ssh) raises an error in Python: FileNotFoundError: [WinError 2] The system cannot find the file specified
You say C:\Windows\System32\OpenSSH\ssh.exe exists, but that it's not found when running from Python. This is likely a result of having a 32 bit version of Python installed, rather than a 64 bit version.
If the path exists elsewhere, but not for Python, that would tend to implicate the file system redirector. Python is probably seeing C:\Windows\SysWOW64 when you tell it to look in C:\Windows\System32. I'd recommend uninstalling whatever Python you have, and explicitly installing a 64 bit version, so it isn't affected by the redirector, and sees the "real" System32.

subprocess.Popen not working in ubuntu (working fine in Windows)

I am right now in the same directory in which the file "lookup.csv" is residing.
I have tried following commands in Python 2.7:
import subprocess
subprocess.Popen("lookup.csv", shell = True)
The above is producing the following error:
lookup.csv : not found
I have double-checked for the working directory, tried lot of available troubleshooting options given in StakExchange, tried the same in Windows (and surprisingly it was working there), what more can I do?
There's no reason why this should work on Windows because lookup.csv clearly is a file which you want to open with open whereas subprocess.Popen creates a new process for working with the lookup.csv binary. Maybe Windows handles process failure differently.

Avoiding shell=True in Popen

I am trying to open a .txt file in Windows. The code is as follows:
subprocess.Popen("C:\folder\file.txt", shell=True)
This works perfectly fine. The default editor is automatically opened and the file is loaded, however, I have read somewhere before that invoking calls through the shell (cmd.exe in Windows) is less safe. How can I do the same without it. Simply setting shell=False is giving me the error:
OSError: [WinError 193] %1 is not a valid Win32 application
Now, I can try this as a workaround:
subprocess.Popen("notepad C:\folder\file.txt")
but this only works if notepad is available, hence loses its generality.
If you are using windows then there is the (non portable) os.startfile command which will take a file path and open it in the default application for that filetype.
In your case you would do:
import os
os.startfile("C:\folder\file.txt")
Note that this method won't work on Linux and Mac OSX, you'll have to have to use their own utilities for this. (open for OSX and xdg-open on Linux) and start them with subprocess.
The feature you try to use is a builtin thing of the windows cmd.exe. Therefore you need to set the shell=True parameter. The cmd.exe knows what to do with the file you hand in.
If you use shell=False, you try to start the file like a programm and hence nothing happens, since .txt files have no exe-header.
Read more about it in the documentation.
Reading further, you can find why using the shell=True parameter can be a security flaw. If you consider to assemble the parameters by user inputs, you should not use this, otherwise nothing speaks against it.
Anyway, I recommend using your second example, because it is explicit. You decide what program to start.
subprocess.Popen("notepad C:\folder\file.txt")

Permissions Error: Within a python script, I need to find a server file in unix system and open it to run commands for the user

In a Unix system, within a python script, I am trying to open a terminal window and start a server. It is my understanding that python has a subprocess module that is supposed to allow such a thing. So:
import subprocess
subprocess.Popen(['path to terminal'])
returns:
OSError: [Errno 13] Permission denied
How do I run this with the right permissions? Or, is there a better, secure way to do what I need?
I'm relatively new to programming, so please reorient the discussion if my question is misguided. Thank you!
Edit: you state that you would like to execute /Applications/Utilities/Terminal.app, so you are apparently running Mac OS X.
Mac OS X .app programs are directories. They can be started with the Mac OS shell command open.
To open the program /path/to/server in a fresh Max OS Terminal session:
import subprocess
termapp=['open','-a','/Applications/Utilities/Terminal.app']
sp=subprocess.Popen(termapp+['/path/to/server'])
There's also a shell-command version of the terminal, so you do not need open -a.
import subprocess
termapp=['/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal']
sp=subprocess.Popen(termapp+['/path/to/server'])
The two ways have subtle differences in how the windows are grouped by the window manager. Each time you do the above you get another terminal process and another icon in the tray. While with -a a new window is opened within the same Terminal main program.

Python subprocess module equivalent for double-click in Windows

I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?
I tried the following line:
subprocess.call("C:/myfile.csv", shell=True)
which throws an error saying:
The syntax of the command is
incorrect.
'C:\' is not recognized as
an internal or external command,
operable program or batch file.
How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.
os.startfile(r'C:\myfile.csv')
(Win32 only. For Mac, run a process with 'open filename'; on Linux/freedesktop-in-general, 'xdg-open filename'.)
I think part of your problem is you're using a unix style slash / as a path separator, instead of the windows backslash . It looks like windows is interpreting /myfile.csv as an argument for the program C:, which is why you're getting that message.
However if you corrected that, I think you'd just get it saying that C:\myfile.csv isn't a program.
I know that this is a bit late, but to do that in python 2.x (not sure about 3) you should use the subprocess module, referencing Popen. Here is the code:
import subprocess
subprocess.Popen(r'explorer /select, "C:\"')
It basically opens the file, and then opens it in the default program.

Categories

Resources