【问题标题】:Communicating between 2 python scripts using popen使用 popen 在 2 个 python 脚本之间进行通信
【发布时间】:2021-07-19 14:01:46
【问题描述】:

假设我们遇到了如图所示的问题。

scriptA.py                               scriptB.py

get directory
modify directory
run scriptB with directory as input
                                -------> get directory
                                         open .txt file
                                         scan its contents
                                <------- return content to scriptA
print content

我的脚本一个例子是:

import os
import subprocess
    
if __name__ == '__main__':
   directory = os.getcwd() + os.sep + 'some extension'
    
   p = subprocess.Popen("python ScriptB.py", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
        
   results = p.communicate(input = str.encode(directory))[0]
    
   print(results)

但现在我不确定如何访问 ScriptB 中的输入。那么communicate 检测到 ScriptB 输出的内容有什么必要?我的例子正确吗?

【问题讨论】:

  • 为什么不将其他脚本作为模块导入,或者是为了练习?
  • 我最近不得不做一些不太相似的事情,对subprocess 感到失望/沮丧,最终改用pexpectpexpect.readthedocs.io/en/stable

标签: python subprocess popen


【解决方案1】:

如 cmets 中所述,一个比您提出的要好得多的解决方案通常是重构 scriptB,这样您就可以从 scriptA 中重构 import 并直接调用其函数,而无需单独的子进程。

如果您不能或不想这样做,最简单的安排是编写 scriptB 以便它接受命令行参数,并将结果打印到标准输出。

results = subprocess.run(
    ['python', 'scriptB.py', directory],
    check=True, text=True, capture_output=True).stdout

请注意shell=True 的缺失,它在这里根本没有添加任何值,并且将命令行相应地划分为字符串列表。或许也可以看看Actual meaning of 'shell=True' in subprocess

如果您需要scriptB.py 接受标准输入上的输入(通常,出于多种原因,这是一个可疑的设计),这并没有太大的不同;

result = subprocess.run(
    ['python', 'scriptB.py'],
    input=directory + '\n',
    check=True, text=True, capture_output=True).stdout

你真的想避免subprocess.Popen(),除非你处于subprocess.run()或其所有者兄弟姐妹无法处理的情况。

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2015-08-04
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多