This question already has answers here:
How to start a background process in Python?
(9 answers)
Closed 4 months ago.
I am trying to write a Raspberry Pi Python-3 script that turns on an IR receiver using a call to os.system() with mode2 as the argument.
When this line of code executes, the mode2 process starts and runs properly (I can see it working in the open terminal) but the rest of the program stalls. There is additional code that needs to run after the os.system("mode2") call.
My question is: How do I start the mode2 process and still allow the rest of the python-3 code to continue executing?
Here is a minimal way to approach this:
A bash script my_process.sh sleeps for 10 seconds, then writes the string "Hello" into a world.txt file:
#!/usr/bin/env bash
sleep 10; echo 'Hello' > world.txt
A python script starts my_process.sh, and prints "Done from Python" when finished.
# File: sample_script.py
import subprocess
if __name__ == "__main__":
subprocess.Popen(["bash", "my_process.sh"])
print("Done from Python.")
Running sample_script.py will write "Done from Python" to the console, and the world.txt file will appear about ten seconds later.
Related
This question already has answers here:
Using module 'subprocess' with timeout
(31 answers)
Closed 7 years ago.
I wrote a program (I ran it in the terminal) that goes through a list of terminal commands (Kali Linux).
import subprocess as sub
import time
sub.call(['airmon-ng', 'start', 'wlan0'])
p = sub.call(['airodump-ng','wlan0mon'])
time.sleep(10)
p.kill()
The last commmand is airodump-ng wlan0mon. Everything works fine (everything is displayed in the terminal (beacons, essid, etc.).
After a specified time I wish to kill the process (airodump-ng wlan0mon).
I don't want to press Ctrl + C by hand!
p.kill() does not work (maybe improper use).
How can I do this? What command should I send through the subprocess module?
The subprocess.call method is a high-level API that waits for the process to terminate before returning its exit code. If you need your main process to continue running while the subprocess runs, you need to use the slightly lower-level API: subprocess.Popen, which starts the process in the background.
Using p = sub.Popen(['airodump-ng','wlan0mon']) instead of p = sub.call(['airodump-ng','wlan0mon']) should work.
I'm writing a program for Windows 7 using Python 2.7.9. This program allows the user to schedule and run a list of scripts and needs to show the output of the scripts in real-time. In order to run the scripts I have the following code:
self.proc = Popen(command, shell=False, stdout=PIPE, stderr=STDOUT)
for line in iter(self.proc.stdout.readline, b''):
print line
This is working and runs the scripts just fine but the issue is that I only see output after the script has finished running which is not acceptable. For example I have a simple program:
from time import sleep
print "test: Can you see me?"
#sys.stdout.flush()
sleep(10)
print "ending"
I do not see any of the print statements until after the sleep time at which point the script ends and everything is printed to the console at once. I've tried a few different approaches but nothing gets it to print in real time. The only thing I have found to work is to make the script I'm running unbuffered by adding the sys.stdout.flush() or adding the following to the beginning of each python script I want to run:
unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stdout = unbuffered
I also need to be able to run other scripts like perl and java so this is not a good fix.
So is there any way to execute scripts from a python program and have the output shown in real time? I'm open to other suggestions as well, maybe there is a better approach than using subprocess that I'm not aware of.
This question already has answers here:
How to terminate a python subprocess launched with shell=True
(11 answers)
Closed 8 years ago.
def example_function(self):
number = self.lineEdit_4.text() #Takes input from GUI
start = "python3 /path/to/launched/script.py "+variable1+" "+variable2+" "+variable3 #Bash command to execute python script with args.
for i in range(0,number):
x = subprocess.Popen(start,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#Launch another script as a subprocess
So, this code launches another Python script for a number of times, each python script contains an infinite while loop, so, I am trying to create a function that kills whatever number of processes are generated by that above function.
I tried stuff like
x.terminate()
But that just does not work, I think that should kill all the sub-processes, but it does not do that, I think it might be killing the last launched process or something along those lines, but my question is, how can I kill whatever number of processes launched by my first function?
Put all the subprocesses in a list instead of overwriting the x variable
def example_function(self):
number = self.lineEdit_4.text() #Takes input from GUI
start = "python3 /path/to/launched/script.py "+variable1+" "+variable2+" "+variable3 #Bash command to execute python script with args.
procs = []
for i in range(0,number):
x = subprocess.Popen(start,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#Launch another script as a subprocess
procs.append(x)
# Do stuff
...
# Now kill all the subprocesses
for p in procs:
p.kill()
This question already has answers here:
How can I stop python.exe from closing immediately after I get an output? [duplicate]
(7 answers)
Closed 9 years ago.
A real noob question.
I just wrote my first Hello World ! python program
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
print ('Hello World !')
return 0
if __name__ == '__main__':
main()
Unfortunately, when I launch it, it opens the terminal for a fraction of a second. How to avoid that it exits straight.
I look for something like pause in Windows command line.
Wait for a keystroke:
raw_input("Press <Enter> to exit.")
This will prompt the user for input and wait until it is received, at which point, the program will exit
There's several solutions:
Launch a command line and then run your Python program in it, with python <your_file>, it'll not exit the console ;
With a good IDE, you can put a breakpoint at the end of your main (example with Pydev) ;
Ask a fake user input, which will freeze the program, waiting for the input
if __name__ == '__main__':
main()
input("Press <Enter> to exit.") # Python 3, raw_input if Py2
This question already has answers here:
Run a program from python, and have it continue to run after the script is killed
(5 answers)
Closed 8 years ago.
I have recently come across some situations where I want to start a command completely independently, and in a different process then the script, equivalent typing it into a terminal, or more specifically writing the command into a .sh or .desktop and double clicking it. The request I have are:
I can close the python window without closing the application.
The python window does not display the stdout from the application (you don't want random text appearing in a CLI), nor do I need it!.
Things I have tried:
os.system waits.
subprocess.call waits.
subprocess.Popen starts a subprocess (duh) closing the parent process thus quits the application
And thats basically all you can find on the web!
if it really comes down to it I could launch a .sh (or .bat for windows), but that feels like a cheap hack and not the way to do this.
If you were to place an & after the command when called from os.system, would that not work? For example:
import os
os.system( "google-chrome & disown " )
import subprocess
import os
with open(os.devnull, 'w') as f:
proc = subprocess.Popen(command, shell=True, stdout=f, stderr=f)
Spawn a child process "the UNIX way" with fork and exec. Here's a simple example of a shell in Python.
import os
prompt = '$ '
while True:
cmds = input(prompt).split()
if len(cmds):
if (os.fork() == 0):
# Child process
os.execv(cmds[0], cmds)
else:
# Parent process
# (Hint: You don't have to wait, you can just exit here.)
os.wait()