简体   繁体   中英

Run a python script from another python script running as a daemon

I have a small python file which just outputs a string:

#!/usr/bin/env python
print("This is a Test")

I can call this python script from another python script like so:

subprocess.call(['python', 'myPythonFile.py'])

And I can see the 'This is a Test' in my source python program.

But I want to call this script from a running Daemon as described here: https://gist.github.com/andreif/cbb71b0498589dac93cb

When I put the call to

    subprocess.call(['python', 'myPythonFile.py'])

In MyDaemon.Run I DO NOT see the output.

How can I do this?

Try using the check_output function to see the actual output in your console

subprocess.check_output(['python', 'myPythonFile.py'])

You can find more info in the subprocess docs

subprocess.call can send its output to a file

tempfile = '/tmp/output.tmp' # better use mktemp

with open( tempfile, 'w') as output:
    response = subprocess.call(
         ['python', 'myPythonFile.py'], 
         stdout=output, 
         stderr=output,
    )
with open( tempfile, 'r') as output:
    # read what happened from output, and decide what to do next
    # or perhaps just feed it into your logging system

A daemon process is characterised by having no controlling terminal, because it is detached from whatever started the daemon. The daemon process is not connected to any console, by definition.

So, if that daemon runs another process:

I want to call this script from a running Daemon

then there is still no controlling terminal, and standard output is by default connected to the null device.

You will need to have the daemon process arrange to have its output somewhere. For example, a log file.

Try the python daemon library for a way to create daemons and nominate specific files (eg a log file you opened) to remain open in the daemon process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM