ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Distribution: Linux Mint, Ubuntu Netbook Edition, et al
Posts: 108
Rep:
Needing help with forking??? a task in Python
Hello,
I'm trying to figure out how to continue execution of a Python program while a background task is going on.
In bash, it is adding "&" to the end as in:
Code:
#! /bin/bash
find / -iname "*.py" > /tmp/all_pys &
echo "looking for all python scripts and putting them in /tmp/all_pys"
(yes, I know I could just put the echo BEFORE the find but I just use it for example)
Say I do that in python (not necessarily running the shell, but perhaps using scriptutil.ffind or something similar), but want to allow the user to be doing something else while running that search in the background, how would I thread, fork, subprocess (not to be confused with the module and Popen) [or whatever I should call it] that?
Distribution: Linux Mint, Ubuntu Netbook Edition, et al
Posts: 108
Original Poster
Rep:
Quote:
Originally Posted by ghostdog74
what is it you are trying to do? Do you want to run Python scripts using the bash shell? Describe more clearly and show your Python code.
This is just an example. I don't have any particular task in mind (yet). I just want to know how it is done for the future. Here is something I just quickly threw together:
Code:
#! /usr/bin/python
from sys import exit
from time import sleep
def calcPI():
#calculates pi to 20 million decimal places
#do math magic here
pass
def fileSearch():
#find file from root down
from subprocess import Popen, PIPE
command = 'find / -iname "*myfile"*'
shell = Popen(command, shell=True, stderr=PIPE, stdin=PIPE, stdout=PIPE)
stdout, stderr = shell.communicate('')
if not stderr:
print stdout
else:
print stderr
if stdout.strip():
print stdout
def longTask3():
#this will take at least 30 mins
sleep(60*30)
def longTask4():
#this will take at least 3 hours
sleep(60*30*3)
def doWhat():
options = {
1: calcPI,
2: fileSearch,
3: longTask3,
4: longTask4,
5: exit
}
text = '''
What would you like to do:
1) Find pi to 20 million decimals
2) Find a file
3) do longTask3
4) do longTask4
5) exit
? '''
while True:
num = raw_input(text)
try: num = int(num)
except ValueError:
print '\nChoose only these options:'
continue
if not num in options:
print '\nTry again with these options:'
continue
doWhateverToForkorThreadorWhatever(options, num)
def doWhateverToForkorThreadorWhatever(options, num):
print '\nrunning option number', num
options[num]()
doWhat()
This is just an example. I don't have any particular task in mind (yet). I just want to know how it is done for the future. Here is something I just quickly threw together:
if what have in mind is to "fork" or call external shell process, do it if you really have no choice otherwise, use Python's own modules to do it.
Quote:
Code:
def fileSearch():
#find file from root down
from subprocess import Popen, PIPE
command = 'find / -iname "*myfile"*'
shell = Popen(command, shell=True, stderr=PIPE, stdin=PIPE, stdout=PIPE)
stdout, stderr = shell.communicate('')
if not stderr:
print stdout
else:
print stderr
if stdout.strip():
print stdout
Use os.walk(). See the Python docs for more. General usage:
Code:
import os
for r,d,f in os.walk(/path):
for file in f:
print os.path.join(r,file)
another related module you might be interested in in future is threading.
Last edited by ghostdog74; 08-29-2010 at 07:38 PM.
Distribution: Linux Mint, Ubuntu Netbook Edition, et al
Posts: 108
Original Poster
Rep:
Quote:
Originally Posted by ghostdog74
if what have in mind is to "fork" or call external shell process, do it if you really have no choice otherwise, use Python's own modules to do it.
Use os.walk(). See the Python docs for more. General usage:
Code:
import os
for r,d,f in os.walk(/path):
for file in f:
print os.path.join(r,file)
another related module you might be interested in in future is threading.
Not necessarily shell scripting processes or tasks. I just used the find file as an example.
The finding pi process would strictly be a Python math process (ah the calculus of it). Also, just as placeholders, my longProcess3 and 4 are Python-only processes (in this case, using time.sleep() to keep it pure Python).
I'll look into the threading module with high hopes. I would like to start a function and have it working in the background as the program continues to run.
What I didn't really point out and should have is that in the flow of the program, I want to run, say, option 1. It will start the function and return to the list allowing me to run another option immediately after the first option was started. Thus, I'm not waiting for the called function to finish before being able to choose another.
Distribution: Linux Mint, Ubuntu Netbook Edition, et al
Posts: 108
Original Poster
Rep:
Quote:
Originally Posted by ghostdog74
. . .another related module you might be interested in in future is threading.
This looks like what I'm looking for. I was hoping implementation was a little easier and quicker (it's hard to beat the efficiency of "(sleep 5 ; echo "done sleeping) &" but I'm sure it adds more flexibility).
I'll do some searching on actual code examples for this module so I can get an idea of it's implementation in the "real world." Any pointers, here, too would be appreciated.
Okay, as an update, I was only posting an example of how to use the os.fork() function. Yes, it can be used in other ways, but to the OP: Just use the function, not the while loop around it. If you EVER use the fork() function in an infinite loop, you will end up with a program that infinitely forks out of control, causing your system to freeze. USE THE FORK OPERATION SPARINGLY!!!!!
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.