I want to launch a shortcut named blender.ink located at "D://games//blender.ink". I have tryed using:-
os.startfile ("D://games//blender.ink")
But it failed, it only launches exe files.
The Python os.startfile function should work fine, but you need to specify a .lnk extension to be a valid Windows shortcut file:
import os
os.startfile (r"D:\games\blender.lnk")
If you need to wait for the application to complete before continuing, then a different approach would be needed as follows:
import win32com.shell.shell as shell
import win32event
se_ret = shell.ShellExecuteEx(fMask=0x140, lpFile=r"D:\games\blender.lnk", nShow=1)
win32event.WaitForSingleObject(se_ret['hProcess'], -1)
Related
I'm a bit turned around on how to execute a shell script file in a Linux environment via Python's subprocess command in Streamlit. Any assistance on what I'm missing is appreciated.
I'm using a shell script called 0_texts.sh to run Pylanguagetool for a grammar check of one text file and return corrections in another text file, like so:
cd /home/user/dir/TXTs/
pylanguagetool text_0.txt > comments_0.txt
This script runs correctly in the Linux terminal, writing a comments_0.txt with appropriate grammar checks from text_0.txt.
I need to create a Python/Streamlit app that runs these shell scripts. In attempting to run this shell script, I've written script.py below:
import os
import subprocess
import sys
subprocess.run(['bash','/home/user/dir/Scripts/0_texts.sh'])
I then run script.py in Streamlit via the code below, keeping with Streamlit's documentation on using subprocess here.
import streamlit as st
import os
import subprocess
import sys
def app():
button1 = st.button("Click me")
if button1:
p = subprocess.run([f"{sys.executable}", "/home/user/dir/pages/script.py"])
st.write(p)
When I execute the script.py via Streamlit, the 0_txts.sh script executes, writing comments_0.txt in the correct directory and providing the following traceback: CompletedProcess(args=['/usr/bin/python3', '/home/user/dir/pages/script.py'], returncode=0). However, the comments_0.txt output contains the error input file is required, as if it can't properly access or read text_0.txt. I've tinkered around trying to find the problem, but have hit a brick wall.
Any suggestions on what I'm missing, or paths forward? Any help greatly appreciated.
I am designing a context menu, in which I use a context menu to redirect to my python script.
Among multiple other options, one option is to launch interactive shell from the script with pre-import commands.
Here is what I have tried so far:
Created Script which imports the pre-requisites start-script.py consists like below:
import os
import sys
MY_MODULE_PATH = "<path/to/my/module>"
sys.path.append("MY_MODULE_PATH")
# follows the imports from module
# ...
# ...
Code-block handling to invoke script to launch as startup
import subprocess
startup_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "start-script.py")
cmd = [sys.executable, "-i", startup_script]
subprocess.check_call(cmd)
Is this is the only way or more better and simple approach then these 2 steps and files?
How would I open a specific file in IDLE through a python script?
I understand that an app could be opened through subprocess:
import subprocess
subprocess.call('C:\\program.exe')
But I can't figure out how to make it open a file.
If it helps, this:
import os.path
import sys
# Enable running IDLE with idlelib in a non-standard location.
# This was once used to run development versions of IDLE.
# Because PEP 434 declared idle.py a public interface,
# removal should require deprecation.
idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if idlelib_dir not in sys.path:
sys.path.insert(0, idlelib_dir)
from idlelib.pyshell import main
main()
also opens IDLE. I checked, and main() does not take any parameters such as files to open.
I am using Windows 10 with Python 3.6.4.
Any help is greatly appreciated.
Here are 2 ways to open any python file through IDLE
import subprocess
p = subprocess.Popen(["idle.exe", path_to_file])
# ... do other things while idle is running
returncode = p.wait() # wait for notepad to exit
OR:
import subprocess
import os
subprocess.call([path_to_idle, path_to_file])
You can also use these methods to open any file with any installed app (How can I open files in external programs in Python?)
One can run IDLE from a command line on any platform with <python> -m idlelib <IDLE args>, where <python> could be 'python', 'python3', or something line 'py -3.8', depending on the platform. <IDLE args> are defined in the "Command line usage" subsection of the IDLE doc, also available within IDLE as Help => IDLE Help.
A possible 'IDLE arg' is the path of a file to be opened in an editor window. Relative paths are relative to the current working directory, which can be changed with the 'cd' command. A working command line can used quoted or turned into a list for a subprocess.run or subprocess.Popen call. In Python code, the working directory is changed with os.chdir('newdir').
I make program in python to open some executable file given by path. I use:
os.startfile(path)
to start program. When i run script.py in IDLE it works fine, but when i make .exe file with pyinstaller when i run it that program i want to open starts to open and closes almost immediately. I tried with different functions like subprocess.Popen(path) and it does the same thing, open and close program after 1 second. Can someone help me? Is there a problem in python functions or in pyinstaller or even windows 10?
The problem is that your code most likely just runs and then the window closes.
You can add import time to your imports and time.sleep(x) or something to keep the window open for x seconds after you run
Read all the way through before doing anything!
Ok so try this:
Put this in a python file called start.py:
import os
import subprocess
#py_command - whatever opens python in cmd
#path - must be full path of file you want to call
def StartPythonScript(path, py_command):
command = 'start cmd /k ' + py_command + " " + path
subprocess.run(command, shell=True)
Now, take the code from file you are calling from the exe, let's say its name is run.py, and put it in a different file, say code.py.
Make sure start.py is in the same folder as run.py
In run.py, put this:
import start
cmd = "py" #change this to whatever opens python in cmd
path = "code.py" #change to the full path of code.py
start.StartPythonScript(path, cmd)
So when you click on the exe, it opens run.py which tells start.py to open code.py, which contains your program.
You can actually merge start.py and run.py, but you can reuse start.py if they are seperate.
OR...
Add import os to your program that is called by the exe.
Add os.system("pause") to the end of your program.
I'm not sure if this will work on an infinitely running program...but try this first to save time.
More info:
How to stop Python closing immediately when executed in Microsoft Windows
Good luck!
I am trying to run 3 python programs simultaneously by running a single python program
I am using the following script in a separate python program sample.py
Sample.py:
import subprocess
subprocess.Popen(['AppFlatRent.py'])
subprocess.Popen(['AppForSale.py'])
subprocess.Popen(['LandForSale.py'])
All the three programs including python.py is in the same folder.
Error: OSError: [Errno 2] No such file or directory
Can someone guide me how can i do it using subprocess.Popen method?
The file cannot be found because the current working directory has not been set properly. Use the argument cwd="/path/to/script" in Popen
It's because your script are not in the current directory when you execute sample.py.
If you three script are in the same directory than sample.py, you could use :
import os
import subprocess
DIR = os.path.dirname(os.path.realpath(__file__))
def run(script):
url = os.path.join(DIR, script)
subprocess.Popen([url])
map(run, ['AppFlatRent.py','AppForSale.py', 'LandForSale.py'])
But honestly, if i was you i will do it using a bash script.
There might be shebang missing (#!..) in some of the scripts or executable permission is not set (chmod +x).
You could provide Python executable explicitly:
#!/usr/bin/env python
import inspect
import os
import sys
from subprocess import Popen
scripts = ['AppFlatRent.py', 'AppForSale.py', 'LandForSale.py']
def realpath(filename):
dir = os.path.realpath(os.path.dirname(inspect.getsourcefile(realpath)))
return os.path.join(dir, filename)
# start child processes
processes = [Popen([sys.executable or 'python', realpath(scriptname)])
for scriptname in scripts]
# wait for processes to complete
for p in processes:
p.wait()
The above assumes that script names are given relative to the module.
Consider importing the modules and running corresponding functions concurently using threading, multiprocessing modules instead of running them as scripts directly.