I have a crazy problem.
I have a cmd to run an exe file and it executes with no errors. The cmd in command prompt is
E:\project\cpp\myfirst.exe
I have to call this exe file within my python script. I use subprocess.call. But I get an error. The code and error is as follows
import subprocess
subprocess.call('E:\\project\\cpp\\myfirst.exe')
The error i get is
ERROR: Could not open myfirst setup file
1
I couldnt find the solution. I also tried os.system call. But still the same error. can you guys help me.
NOTE: the exe file is generated from a cpp code
thanks
The program seems to be seeking for some configuration file in the working directory, which is not always the same as the one where the executable is. Try instead:
import subprocess
subprocess.call('myfirst.exe', cwd=r'E:\project\cpp')
If you have written myfirst.exe yourself, consider changing the lookup logic so that it checks the executable's own directory.
Under Linux I have always found the popen mechanism to be more reliable.
from subprocess import Popen, PIPE process = Popen(['swfdump',
'/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE) stdout, stderr =process.communicate()
Answer taken from
How to use subprocess popen Python
Related
I am a newbie to python and would like to seek some advice. I having a script now where the function of this script can only be executed after I run a command i.e. python run trial.py. However, I would like to automate this process by using a subprocess function in a new python file called 'run.py' to run the trial.py script.
After that, I would wish to convert run.py file into an exe file to ease the execution for other users.
I have tried to perform the below steps.
1. saved the scripts (trial.py & run.py) in same directory.
2. Execute both of the files in same conda virtual environment.
3. Successfully execute run.py by using ```subprocess.run('xxx run trial.py')```
4. Converted the run.py into an exe file
5. Tried to execute the exe file and it is running, but **failed** to show the output that suppose to be appeared after running trial.py.
Would like to seek advice is any steps on above did wrongly or need to be improvised? I need to deal with confidential data hence the easiest way I can do is by using pyinstaller to allow another user to execute.
Hope to hear some advice
UPDATE
I had tried to use the codes below,
import subprocess
import sys
from subprocess import PIPE, STDOUT
command ='python run trial.py'
run = subprocess.Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
Now the exe file is able to be generated and able to run, but it doesn't appear the expected output. It ended without any error message. It works well when I run the script in python..
Wish to hear advice from all of you..
With subprocess, you can try it:
command = 'Your command' # Example: command = 'python trial.py'
process = subprocess.Popen(command, shell=True, stdout=sys.stdout, stderr=sys.stderr)
I would wish ... to ease the execution for other users.
As I've understood your case, using subprocess and making an exe file out of your python file (which is not an easy task) is not a good fit for you.
Instead, I recommend you to have a look at make files as they are well-known for simplifying your commands.
for example you can have a make file like this:
run:
python trial.py
And users can simply run make run, and python trial.py will run instead.
The possibilities are endless.
You can also make a bash file that is an executable,
# !/bin/bash
python trial.py
And it will simply run like exe files.
From python, I need to run a python file inside of git bash, while running in Windows.
That is, I have a configuration script written in python that calls other python scripts. Unfortunately, some of them use Unix commands, so they must be run using git bash in Windows.
Currently I'm using this:
cmd = f'{sys.executable} mydependency.py'
pipe = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
# waiting for pipe is handled later...
However, this doesn't work, giving me a cannot execute binary file message. How can I get it to run?
PS: For slightly more context, mydependency.py is actually the amalgamate.py script from the simdjson (https://github.com/simdjson/simdjson) project.
EDIT:
I have also attempted the following:
Switch to run or call instead of subprocess.Popen
Use f'{git_bash_path} {sys.executable} mydependency.py'
Change the shell and executable parameters of Popen,run and call
I found a solution:
cmd = git_bash_path # Found with glob.
pipe = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
pipe.communicate(input=f'{sys.executable} mydependency.py'.encode())
I'm not entirely sure why this works, if anyone has an explanation I'd be glad to hear it.
I am trying to run a shell script using through Python using subprocess.Popen().
The shell script just has the following lines:
#!/bin/sh
echo Hello World
Following is the Python code:
print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
shellscript.wait()
for line in shellscript.stdout.readlines():
print(line)
print("SHELL SCRIPT RUN ENDED")
However, on running this, I am only getting the following output:
RUNNNING SHELL SCRIPT NOW
SHELL SCRIPT RUN ENDED
i.e. I am not getting the shell script output in between these 2 lines.
Moreover, when I remove the stderr=subprocess.PIPE part from the subprocess, I get the following output:
RUNNNING SHELL SCRIPT NOW
'km' is not defined as an internal or external command.
SHELL SCRIPT RUN ENDED
I am not able to understand how to resolve this, and run the shell script properly. Kindly guide. Thanks.
UPDATE:
I also tried the following change:
print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = shellscript.communicate()
print(out)
print("SHELL SCRIPT RUN ENDED")
I get the following output:
RUNNNING SHELL SCRIPT NOW
b''
SHELL SCRIPT RUN ENDED
The simple and straightforward fix is to not use bare Popen for this.
You also don't need a shell to run a subprocess; if the subprocess is a shell script, that subprocess itself will be a shell, but you don't need the help of the shell to run that script.
proc = subprocess.run(
['km/example/example1/source/test.sh'],
check=True, capture_output=True, text=True)
out = proc.stdout
If you really need to use Popen, you need to understand its processing model. But if you are just trying to get the job done, the simple answer is don't use Popen.
The error message actually looks like you are on Windows, and it tries to run km via cmd which thinks the slashes are option separators, not directory separators. Removing the shell=True avoids this complication, and just starts a process with the requested name. (This of course still requires that the file exists in the relative file name you are specifying. Perhaps see also What exactly is current working directory? and also perhaps switch to native Windows backslashes, with an r'...' string to prevent Python from trying to interpret the backslashes.)
I was doing an exersize with the following task:
Write a python program to call an external command in Python.
As I could not solve it by my own I looked up the solution:
from subprocess import call
call(["ls", "-l"])
But the solution threw an Error:
FileNotFoundError: [WinError 2]
I also tried adding shell=True and for example leaving out the brackets like following:
subprocess.call('ls -l', shell=True)
In this case it tells me that the command "ls" could not be found.
I am working on windows 10,Python 3.8.2 32 bit
I am kind of lost and would be glad if someone could help.
Thank you!
ls is not a valid Windows CMD command.
For learning purpose, you may try CD for printing current directory, ie
import subprocess
subprocess.call(['CD'], shell=True)
I'm currently running an OpenELEC (XBMC) installation on a Raspberry Pi and installed a tool named "Hyperion" which takes care of the connected Ambilight. I'm a total noob when it comes to Python-programming, so here's my question:
How can I run a script that checks if a process with a specific string in its name is running and:
kill the process when it's running
start the process when it's not running
The goal of this is to have one script that toggles the Ambilight. Any idea how to achieve this?
You may want to have a look at the subprocess module which can run shell commands from Python. For instance, have a look at this answer. You can then get the stdout from the shell command to a variable. I suspect you are going to need the pidof shell command.
The basic idea would be along the lines of:
import subprocess
try:
subprocess.check_output(["pidof", "-s", "-x", "hyperiond"])
except subprocess.CalledProcessError:
# spawn the process using a shell command with subprocess.Popen
subprocess.Popen("hyperiond")
else:
# kill the process using a shell command with subprocess.call
subprocess.call("kill %s" % output)
I've tested this code in Ubuntu with bash as the process and it works as expected. In your comments you note that you are getting file not found errors. You can try putting the complete path to pidof in your check_output call. This can be found using which pidof from the terminal. The code for my system would then become
subprocess.check_output(["/bin/pidof", "-s", "-x", "hyperiond"])
Your path may differ. On windows adding shell=True to the check_output arguments fixes this issue but I don't think this is relevant for Linux.
Thanks so much for your help #will-hart, I finally got it working. Needed to change some details because the script kept saying that "output" is not defined. Here's how it now looks like:
#!/usr/bin/env python
import subprocess
from subprocess import call
try:
subprocess.check_output(["pidof", "hyperiond"])
except subprocess.CalledProcessError:
subprocess.Popen(["/storage/hyperion/bin/hyperiond.sh", "/storage/.config/hyperion.config.json"])
else:
subprocess.call(["killall", "hyperiond"])