I need to launch an external program from my python script.
This program crashes, so I need to get a core dump from it.
what can i do?
Check out the python resource module. It will let you set the size of core files, etc., just like the ulimit command. Specifically, you want to do something like
resource.setrlimit(resource.RLIMIT_CORE, <size>)
before launching your target program.
My guess at usage (I haven't done this myself) is:
import resource
import subprocess
resource.setrlimit(resource.RLIMIT_CORE,
(resource.RLIM_INFINITY,
resource.RLIM_INFINITY))
command = 'command line to be launched'
subprocess.call(command)
# os.system(command) would work, but os.system has been deprecated
# in favor of the subprocess module
Related
I want to run a python script that can execute OS (linux) commands , I got few modules that helps me in doing that like os, subprocess . In OS module am not able to redirect the output to a variable . In subprocess.popen am not able to use variable in the arguments. Need someone help in finding the alternative .
Am trying to run some OS commands from python script . for example df -h output. It works fine with by using some modules like os or subprocess .But am not able to store those output to any variable .
Here am not able to save this output to a variable . How do I save this to a variable.
i saw multiple other options like subprocess.Popen but am not getting proper output.
Below program i used subprocess module but here I have another issue , as the command is big am not able to use variables in subprocess.Popen.
You can use the subprocess method check_output
import subprocess
output = subprocess.check_output("your command", shell=True)
see previously answered SO question here for more info: https://stackoverflow.com/a/8659333/3264217
Also for more info on check_output, see python docs here:
https://docs.python.org/3/library/subprocess.html#subprocess.check_output
Use either subprocess or pexpect depending on what is your exact use case.
subprocess can do what os.system does and much more. If you need to start some command, wait for it to exit and then get the output, subprocess can do it:
import subprocess
res = subprocess.check_output('ls -l')
But if you need to interact with some command line utility, that is repeatedly read/write, then have a look at pexpect module. It is written for Unix systems but if you ever want to go cross-platform, there is a port for Windows called winpexpect.
spawn's attribute 'before' is probably what you need:
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
(see the docs)
I'm trying to install ansicon on Windows 8.1. I extracted the files and got to the level that I need to call ansicon -i. When I type this in my cmd and run python scripts that works great but when I call t from python by os.system('ansicon -i') that doesn't work and seems like it doesn't have any influence on the cmd.
Why os.system('ansicon -i') doesn't work and what alternative method can I use from within python?
First off, it’s not the -i flag that really does the work. -i only tells it to add itself to AutoRun. The -p flag that -i implies is what really does the work: -p tells it to inject a DLL into the parent process, and therein lies the problem: when you use os.system, you spawn a shell, which then runs the command you give it. But then you have Python running cmd running ansicon, and ansicon will inject into cmd, and then cmd, having finished its work, will exit.
Rather than using os.system, use the subprocess module, e.g.:
subprocess.check_call(['ansicon', '-p'])
The subprocess module (unlike os.system) will execute the command directly without a shell in-between (unless you pass shell=True). Then Python will spawn ansicon, and ansicon will inject into Python, as desired.
That said, rather than having ansicon inject itself into Python, Python could probably just load the DLL itself, avoiding some hardship:
import sys
import math
import ctypes
bitness = 1 << round(math.log2(round(math.log2(sys.maxsize + 1))))
ctypes.WinDLL('ANSI{}.DLL'.format(bitness))
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"])
For example I know this method: os.system("cmd") but it starts console in the directory of the script or in the dir of the interpreter, is there a way to gain control of this issue ?
The prefered method for subprocess forking is the «subprocess» module.
You can specify a working directory for the command. e.g. :
import subprocess
subprocess.check_call( ['ls'], cwd='/tmp' )
See documentation for the subprocess module.
You can use os.chdir(target_directory) to change your program's working directory before starting the external application.
i have a python script which should invoke a .exe file to get some result. That .exe file is invoking a new windows command prompt(shell) . i dont need any output from the .exe file.
i 'm using
os.system('segwin.exe args') in my script where segwin is an executable.
now my question is : i need to stop invoking cmd prompt
kudos to all
sag
Try this (untested):
import subprocess
CREATE_NO_WINDOW = 0x08000000
args = [...]
subprocess.check_call(["segwin.exe"] + args, creationflags=CREATE_NO_WINDOW)
Note that check_call checks the return code of the launched subprocess and raises an exception if it's nonzero. If you don't want that, use call instead.
In general, avoid os.system() and use the subprocess module whenever possible. os.system() always starts a shell, which is nonportable unnecessary on most cases.
This is actually specific to Windows. Windows has decided that segwin.exe is a console-based application (uses the Console subsystem from the Windows C interface).
I know how to invoke an prompt for apps that don't necessarily want one, but not the reverse, you could try using this, or this.