How can I call a python script from a python script

2024/10/2 8:37:24

I have a python script 'b.py' which prints out time ever 5 sec.

while (1):print "Start : %s" % time.ctime()time.sleep( 5 )print "End : %s" % time.ctime()time.sleep( 5 )

And in my a.py, I call b.py by:

def run_b():print "Calling run b"try:cmd = ["./b.py"]p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)for line in iter(p.stdout.readline, b''):print (">>>" + line.rstrip())except OSError as e:print >>sys.stderr, "fcs Execution failed:", e  return None  

and later on, I kill 'b.py' by:PS_PATH = "/usr/bin/ps -efW"

def kill_b(program):try:cmd = shlex.split(PS_PATH)retval = subprocess.check_output(cmd).rstrip()for line in retval.splitlines():if program in line:print "line =" + linepid = line.split(None)[1]os.kill(int(pid), signal.SIGKILL)except OSError as e:print >>sys.stderr, "kill_all Execution failed:", eexcept subprocess.CalledProcessError as e:print >>sys.stderr, "kill_all Execution failed:", erun_b()
time.sleep(600)
kill_b("b.py")

I have 2 questions. 1. why I don't see any prints out from 'b.py' and when I do 'ps -efW' I don't see a process named 'b.py'? 2. Why when I kill a process like above, I see 'permission declined'?

I am running above script on cygwin under windows.

Thank you.

Answer
  1. Why I don't see any prints out from 'b.py' and when I do 'ps -efW' I don't see a process named 'b.py'?

    Change run_b() lines:

    p = subprocess.Popen(cmd,stdout=sys.stdout,stderr=sys.stderr)
    

    You will not see a process named "b.py" but something like "python b.py" which is little different. You should use pid instead of name to find it (in your code "p.pid" has the pid).

  2. Why when I kill a process like above, I see 'permission declined'?

    os.kill is supported under Windows only 2.7+ and acts a little bit different than posix version. However you can use "p.pid". Best way to kill a process in a cross platform way is:

    if platform.system() == "Windows":subprocess.Popen("taskkill /F /T /PID %i" % p.pid, shell=True)
    else:os.killpg(p.pid, signal.SIGKILL)
    

killpg works also on OS X and other Unixy operating systems.

https://en.xdnf.cn/q/70868.html

Related Q&A

Read EXE, MSI, and ZIP file metadata in Python in Linux

I am writing a Python script to index a large set of Windows installers into a DB. I would like top know how to read the metadata information (Company, Product Name, Version, etc) from EXE, MSI and ZIP…

IllegalArgumentException thrown when count and collect function in spark

I tried to load a small dataset on local Spark when this exception is thrown when I used count() in PySpark (take() seems working). I tried to search about this issue but got no luck in figuring out wh…

Check if string does not contain strings from the list

I have the following code: mystring = ["reddit", "google"] mylist = ["a", "b", "c", "d"] for mystr in mystring:if any(x not in mystr for x in…

How do I conditionally include a file in a Sphinx toctree? [duplicate]

This question already has answers here:Conditional toctree in Sphinx(4 answers)Closed 8 years ago.I would like to include one of my files in my Sphinx TOC only when a certain tag is set, however the ob…

Use BeautifulSoup to extract sibling nodes between two nodes

Ive got a document like this:<p class="top">I dont want this</p><p>I want this</p> <table><!-- ... --> </table><img ... /><p> and all tha…

Put HTML into ValidationError in Django

I want to put an anchor tag into this ValidationError:Customer.objects.get(email=value)if self.register:# this address is already registeredraise forms.ValidationError(_(An account already exists for t…

python os.listdir doesnt show all files

In my windows7 64bit system, there is a file named msconfig.exe in folder c:/windows/system32. Yes, it must exists.But when i use os.listdir to search the folder c:/windows/system32, I didnt get the fi…

how to save modified ELF by pyelftools

Recently Ive been interested in ELF File Structure. Searching on web, I found an awesome script named pyelftools. But in fact I didnt know the way to save the modified ELF; ELFFile class doesnt have an…

Access train and evaluation error in xgboost

I started using python xgboost backage. Is there a way to get training and validation errors at each training epoch? I cant find one in the documentation Have trained a simple model and got output:[09…

Gtk* backend requires pygtk to be installed

From within a virtual environment, trying to load a script which uses matplotlibs GTKAgg backend, I fail with the following traceback:Traceback (most recent call last):File "<stdin>", l…