subprocess
。这个模块允许您在新的进程中运行一个命令或脚本,并获取其输出。以下是一个简单的示例,演示如何在另一个Python程序中调用已写好的Python程序:
python复制代码import subprocess # 调用已写好的Python程序 result = subprocess.run(['python', 'path/to/your/program.py'], stdout=subprocess.PIPE) # 打印程序的输出 print(result.stdout.decode('utf-8'))
在上面的代码中,subprocess.run()
函数接受一个命令列表,并使用默认的shell=False参数。这将在新的进程中运行命令,并等待命令完成。stdout=subprocess.PIPE
参数告诉subprocess
模块将程序的输出捕获到管道中。
然后,您可以使用result.stdout
属性获取程序的输出。由于输出是字节类型,因此需要使用decode()
方法将其转换为字符串类型。
请注意,您需要将path/to/your/program.py
替换为您实际要调用的Python程序的路径。
小黑屋|Archiver|手机版|su.sseuu.com ( 粤ICP备12005776号 )
GMT+8, 2024-5-15 14:28 , Processed in 0.034219 second(s), 16 queries .
Powered by Discuz! X3.4 Licensed
© 2001-2013 Comsenz Inc.