我试图通过使用subproccess.popen调用从一个程序(program1)运行代码。程序2(被调用的程序)不显示记录器语句。在下面的示例代码中,program1调用program2并为每个代码设置日志记录。
program1.py
import subprocess
import logging
import sys
def configure_logging(name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
logger = configure_logging(__name__)
python_path = "Path/to/specific/pythonexe"
py_path = "Path/to/program2.py"
cmd = "{} {}".format(python_path,py_path)
logger.info("Cmd: {}".format(cmd))
cmd = cmd.split()
proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
program2.py
import logging
def logstuff(name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
def main():
logger.info("hi")
print("hi2")
if __name__ == "__main__":
logger = logstuff(__name__)
main()
使用上面的安装程序1会调用program2,但是logger.info语句不会被打印出来,只有print()语句会被打印出来。
我无法导入program2,因为它依赖于Anaconda环境中封装的特定python版本。
我期望的输出是将logger.info和随后的所有logger记录打印到终端,那么我将如何实现这一目标?
答案 0 :(得分:1)
我相信您搞乱了记录器的设置。还有stdout PIPE的subprocess.Popen对我来说不起作用。这就是我在本地工作的成果,希望对您有所帮助。
program1.py
import logging
import subprocess
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
python_path = 'python'
py_path = 'program2.py'
cmd = '{} {}'.format(python_path, py_path)
logger.info('Cmd: {}'.format(cmd))
cmd = cmd.split()
subprocess.call(cmd)
program2.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
def main():
logger.info('hi program2 here')
if __name__ == '__main__':
main()
输出:
$ python program1.py
2018-11-14 15:38:53,905:__main__:Cmd: python program2.py
2018-11-14 15:38:53,917:__main__:hi program2 here