I am using os.startfile('C:\\test\\sample.exe') to launch the application. I don't want to know the application’s exit status and I just want to launch the exe.
I need to pass the argument to that exe like 'C:\\test\\sample.exe' -color
Please suggest a method to run this in Python.
You should use the subprocess module instead of os.startfile or os.system in every case that I'm aware of.
import subprocess
subprocess.Popen([r'C:\test\sample.exe', '-color'])
You could, as #Hackaholic suggests in the comments, do
import os
os.system(r'C:\test\sample.exe -color')
But this is no simpler, and the docs for os recommend the use of subprocess instead.
Create a batch file sam_ple.bat with the following commands and arguments
cd C:\test\
start sample.exe -color
Then put sam_ple.bat in the same directory as your script.py file
Enter the following line of code in python to launch the exe:
os.startfile('.\sam_ple.bat')
Related
action_publisher = subprocess.Popen(
["bash", "-c", "/opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start"],
env={'ROS_MASTER_URI': 'http://10.42.0.49:11311\''})
I tried to run it shell=True and shell=False. Also calling it with bash or just running my executable and I am always getting an error:
Traceback (most recent call last):
File "/opt/ros/melodic/bin/rostopic", line 34, in <module>
import rostopic
ImportError: No module named rostopic
How can I make a call of a shell executable with open through python removing this issue? Tried all combination possible and also other stack proposed solution and still, it tries to import the executable instead of running it on a shell.
I can identify several problems with your attempt, but I'm not sure I have identified them all.
You should use subprocess.check_call or subprocess.run if you just want the subprocess to run, and your Python script to wait for that to complete. If you need to use raw subprocess.Popen(), there are several additional required steps of plumbing which you need to do yourself, which check_call or run will perform for you if you use these higher-level functions.
Your use of env will replace the variables in the environment. Copy the existing environment instead so you don't clobber useful settings like PYTHONPATH etc which may well be preventing the subprocess from finding the library it needs.
The shell invocation seems superfluous.
The stray escaped single quote at the end of 'http://10.42.0.49:11311\'' definitely looks wrong.
With that, try this code instead; but please follow up with better diagnostics if this does not yet solve your problem completely.
import subprocess
import os
# ...
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://10.42.0.49:11311'
action_publisher = subprocess.run(
["/opt/ros/melodic/bin/rostopic", "pub", "-r", "20",
"/robot_operation", "std_msgs/String", "start"],
env=env, check=True)
If rostopic is actually a Python program, a better solution altogether might be to import it directly instead.
It sounds like the code of that file is trying to import the Python module. If you're getting that import error even when you try to execute the file in bash/from a shell, then it has nothing to do with subprocess.Popen.
From the traceback, it looks like it's a Python file itself and it's trying to import that module, which would explain why you see the issue when executing it from a shell.
Did you go through the installation correctly, specifically the environment setup? http://wiki.ros.org/melodic/Installation/Ubuntu#melodic.2FInstallation.2FDebEnvironment.Environment_setup
It sounds like you need to source a particular file to have the correct paths available where the Python module is located so it can be found when you execute the script.
As far as I can see, your .Popen command will try to execute
bash -c /opt/ros/melodic/bin/rostopic pub -r 20 /robot_operation std_msgs/String start
while bash -c has to be followed by a string. Thus, you may need to add single quotes.
I have some codes that will take time to run for a while. Is it possible that I create a new file that has a code like
import run001
import run002
import run003
and run this in cmd to make it automatically run other three .py files (run001.py, run002.py, run003.py) from the same folder? This import way works only the first file but not automatically continue the second one.
Yes we can call a command in a python script directly with the use of either
subprocess module or os.system. Here is the link for official documentation.
subprocess
os.system
Though i would suggest you to stick to subprocess module as it is newer and provides more control to user on the other hand os.system just spawns a process and returns the return code
subprocess module allows us to spawn new process through our Python script, so let us assume you want to list all the files in your directory, this can be achieved by a simple call to subprocess.call()
import subprocess as sub
sub.call(yourCommand) #to pass a single command
sub.call(commandList) #to pass a multiple commands
In my script, I need to bring up the command prompt which I have not had any issues in creating:
subprocess.Popen([r"cmd.exe"])
That is essentially what I have done so far. I have some arguments that want to be placed in this prompt, that I want automatically ran when I run the script.
What I would like to do is change my directory in the prompt using only Python. Would anybody have any idea how to get there?
subprocess.Popen takes a keyword argument to specify the current working directory. Simply do this:
subprocess.Popen(r"cmd.exe", cwd = "my/lovely/directory/", "more-args")
Well I have no idea about subprocess, but you could use the os module to change directories, start command prompt, run a batch program, etc.
import os
os.chdir('blah')
os.system('start something.bat')
Depends on if you strictly need to use subprocess. Hope that helps though!
Here is the problem...
I'm writing very small plugin for Blender,
I have 10 python scripts, they parsing different file formats by using command-line, and I have a Main Python script to run all other scripts with proper commands...
for example, "Main.py" include:
txt2cfg.py -inFile -outFile...
ma2lxo.py -inFile -outFile...
Blender already include Python, so I can run "Main.py" from Blender, But I need it to work with both PC and MAC, and also doesn't require Python installation, so I can't use:
execfile(' txt2cfg.py -inFile -outFile ')
os.system(' ma2lxo.py -inFile -outFile ')
or even import subprocess
because they required Python installation in order to run *.py files.
Sorry for language
Thanks
If you really need to execute a python script in a new process and you don't know where the interpreter you want is located then use the sys module to help out.
import sys
import subprocess
subprocess.Popen((sys.executable, "script.py"))
Though importing the module (dynamically if need be) and then running its main method in another script is probably a better idea.
for example, "Main.py" include:
txt2cfg.py -inFile -outFile...
ma2lxo.py -inFile -outFile...
Two things.
Each other script needs a main() function and a "main-import switch". See http://docs.python.org/tutorial/modules.html#executing-modules-as-scripts for hints on how this must look.
Import and execute the other scripts.
import txt2cfg
import ma2lxo
txt2cfg.main( inFile, outFile )
ma2lxo.main( inFile, outFile )
This is the simplest way to do things.
Two options:
Use py2exe to bundle the interpreter with the scripts.
Import the modules and call the functions automatically.
Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
>>> exec(File) ???
It should be possible to execute the script more than one time.
Use execfile('script.py') but it only work on python 2.x, if you are using 3.0 try exec(open('script.py').read())
import file without the .py extension will do it, however __name__ will not be "__main__" so if the script does any checks to see if it's being run interactively you'll need to bypass them.
Alternately, if you're wanting to have a look at the environment after the script runs try python -i script.py
EDIT: To load it again
file = reload(file)
You might want to look into IPython, a more powerful interactive shell. It has various "magic" commands including %run script.py (which, of course, runs the script and leaves any variables it defined for you to examine).
You can also use the subprocess module. Something like:
>>> import subprocess
>>> proc = subprocess.Popen(['./script.py'])
>>> proc.communicate()
You can run any system command using python:
>>>from subprocess import Popen
>>>Popen("python myscript.py", shell=True)
The easiest way to do it is to use the os module:
import os
os.system('python script.py')
In fact os.system('cmd') to run shell commands. Hope it will be enough.