在python中解析带有空格的命令行参数 [英] Parsing Command line arguments in python which has spaces

查看:1790
本文介绍了在python中解析带有空格的命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从ant调用脚本.我从调用方得到它作为单个字符串,但是python奇怪地将其视为两个单独的字符串.我有脚本可以读取文件名及其在Windows中的路径.文件夹结构之间可能有空格,也可能没有空格

I am invoking the script from ant . I am getting it as a single string from the caller but python is strangely treating it as two individual strings.I have script that reads a file name with it's path in windows. The folder structure may or may not have spaces in between

这里是一个示例

test.py D:/test/File Name

我知道可以使用optparse完成此操作.有什么办法可以将参数作为单个参数读取 就像我想在sys.argv [index]中获取它(作为单个字符串).我已经厌倦了以'和'为前缀,但是没有成功.

I know this can be done using optparse. Is there any way that i can read the param as single argument like i want to get it in sys.argv[index] (as a single string). I have tired prefixing with ' and " but with no success.

推荐答案

您传递用引号引起来的文件夹名称:

You pass the folder name wrapped in quotes:

test.py "D:\test\File Name"

sys.argv[1]将包含文件夹路径,包括空格.

sys.argv[1] will contain the folder path, spaces included.

如果出于某些原因不能引用文件夹名称,则需要使用ctypes模块并使用Win32 API的GetCommandLine函数.这是一个功能示例.

If for some reason you cannot quote the folder name, you will need to use the ctypes module and use the Win32 API's GetCommandLine function. Here's a functional example.

这篇关于在python中解析带有空格的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆