【问题标题】:What is the difference between Python 2 & Python 3 with stdin.write?Python 2 和 Python 3 与 stdin.write 有什么区别?
【发布时间】:2020-05-06 18:49:47
【问题描述】:

此代码应启动 CMD 并将字符串写入文件。 它适用于 Python 2 但不适用于 Python 3?

import subprocess

self.process = subprocess.Popen("cmd.exe", shell=True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE,cwd=None,env=None)

Python 2(这工作)

self.process.stdin.write("echo It Works >> k:\\test_Python2.txt\n")

Python 3(为什么这不起作用???)

self.process.stdin.write(("echo It Works >> k:\\test_Python3.txt\n").encode('ascii'))

【问题讨论】:

  • 你判断“这行得通”vs“这行不通”的标准是什么?
  • 我不知道 2020 年 1 月的 Python 2 是什么。

标签: python subprocess stdin popen


【解决方案1】:

我找到了... 在 Python 3 中,您应该关闭或刷新以完成写入

例如:

导入子流程

self.process = subprocess.Popen("cmd.exe", shell=True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE,cwd=None,env=None)

self.process.stdin.write(("echo It Works >> k:\test_Python3.txt\n").encode())

现在你必须冲洗或关闭...

self.process.stdin.close()

self.process.stdin.flush()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2013-10-12
    • 2011-06-22
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多