简体   繁体   English

Python子进程POpen目录处理

[英]Python Subprocess POpen Directory Handling

I am very new to python and still trying to learn the craft as best as I can on my own. 我是python的新手,仍然尝试自己动手学习最好的技巧。 I started to get into automation recently and one of the not so sexy things I'm trying to automate is the automation of Microsoft Baseline Security Analyzer. 我最近开始涉足自动化领域,而我要自动化的一件不太性感的事情是Microsoft Baseline Security Analyzer的自动化。 All it does is check for the patches that are on the machine and which ones are missing, simple right? 它所做的只是检查计算机上的补丁程序以及缺少的补丁程序,对吗?

Anyways, the part that I'm stuck on is that I'm trying to execute the application to run the scan on multiple hostnames located in a text file. 无论如何,我遇到的问题是我试图执行应用程序以对位于文本文件中的多个主机名运行扫描。 The command that I'm using looks like this: 我正在使用的命令如下所示:

subprocess.Popen(['mbsacli','/listfile','"C:\Users\me\Desktop\test.txt"', '/n', 'os+iis+sql+password'])

The part that is getting an issue is with the way python is handling the directory path. 出现问题的部分是python处理目录路径的方式。 What I mean by that is that it tells me the following: 我的意思是,它告诉我以下内容:

Error: Cannot open file C:\Users\me\Desktop        est.txt

The giant blank space between Desktop and "est.txt" is whats the issue, it should be test.txt first of all but its not handling the slashes() cleanly. 问题是桌面和“ est.txt”之间的巨大空白,首先应该是test.txt,但不能干净地处理slashes()。

Any help would be very helpful, thank you. 任何帮助都将非常有帮助,谢谢。

EDIT 编辑

So far I've tried the following: 到目前为止,我已经尝试了以下方法:

subprocess.Popen(['mbsacli','/listfile','r C:\Users\dxd0857\Desktop\test.txt', '/n', 'os+iis+sql+password'])

subprocess.Popen(['mbsacli','/listfile','C:\\Users\\dxd0857\Desktop\\test.txt', '/n', 'os+iis+sql+password'])

subprocess.Popen(['mbsacli','/listfile','r C:\\Users\\dxd0857\\Desktop\\test.txt', '/n', 'os+iis+sql+password'])

the result is still the same error: 结果仍然是相同的错误:

Error: Cannot open file r C:\Users\me\Desktop      est.txt

What happens is that the \\ character is parsed as special character, where \\t means tab. 发生的是\\字符被解析为特殊字符,其中\\t表示制表符。

Therefore you have to either use \\\\ for backslashes: 因此,您必须对反斜杠使用\\\\

subprocess.Popen(['mbsacli', 
                  '/listfile', 'C:\\Users\\me\\Desktop\\test.txt', 
                  '/n', 'os+iis+sql+password'])

...or use raw string instead (thanks @tripleee , @eryksun ): ...或改用原始字符串(感谢@tripleee@eryksun ):

subprocess.Popen(['mbsacli', 
                  '/listfile', r'C:\Users\me\Desktop\test.txt', 
                  '/n', 'os+iis+sql+password'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM