如何在python中将变量传递给subprocess.Popen.stdin.write()

问题描述

我正在使用子进程库中的 Popen 并希望将变量传递给 popen.stdin.write 以执行 bat 文件。我希望通过

执行我的 bat 文件

1. Running multiple Appium servers,and sending one session to each server 2. Running one Appium server,and sending multiple sessions to it 3. Running one or more Appium servers behind the Selenium Grid Hub,and sending all sessions to the Grid Hub 4. Leveraging a cloud provider (which itself is running many Appium servers,most likely behind some single gateway)

我的代码

C:\Users\7zx3we\test.bat chinni 

但这给了我一个语法错误文件来运行。有人可以帮我解决这个问题吗?

解决方法

两件事:

  1. 如果要在文本模式下打开 stdin,则需要定义编码。您可以通过指定 encoding 参数来执行此操作:
Popen('cmd.exe`,stdin=PIPE,stdout=PIPE,encoding='utf8')
  1. 您需要对路径中的反斜杠进行转义,否则它们将被评估为错误的值,例如,\UUnicode escape sequence 开头,而 \t 是制表符:
p.stdin.write('C:\\Users\\7zx3we\\test.bat ' + name)