简体   繁体   English

osx python-如何解码sys.argv?

[英]osx python - how do I decode sys.argv?

I don't think I'm even using funky characters - just trying to pass in a "-d" but my dash seems to get munged. 我认为我甚至没有在使用时髦的字符-只是尝试传递“ -d”,但是我的破折号似乎变得刺耳了。 If I just print sys.argv[1] it looks okay, but if I print the entire list sys.argv, I can see funky characters instead of my dash. 如果仅打印sys.argv [1],就可以了,但是如果打印整个列表sys.argv,则可以看到时髦的字符,而不是破折号。 Mac OSX 10.6.8 Python 2.6.1 Mac OSX 10.6.8 Python 2.6.1

#!/usr/bin/env python
import sys
if __name__ == "__main__":
    try:
        print "SVH FLAG sys.argv ",sys.argv

        num_args = len(sys.argv)
        for i in range(0,num_args):
            print "SVH FLAG sys.argv[",i,"] ",sys.argv[i]

    except:
        print "problem with sys.argv"

Which gives me this when I call it with -d: ./deleteme.py –d /Library/Python/2.6/site-packages 当我用-d调用时,这给了我:./deleteme.py –d /Library/Python/2.6/site-packages

SVH FLAG sys.argv  ['./deleteme.py', '\xe2\x80\x93d', '/Library/Python/2.6/site-packages']
SVH FLAG sys.argv[ 0 ]  ./deleteme.py
SVH FLAG sys.argv[ 1 ]  –d
SVH FLAG sys.argv[ 2 ]  /Library/Python/2.6/site-packages

That funky string on the first line of output seems to really mess up something like optparse, which doesn't see my dash. 输出的第一行上的那个时髦的字符串似乎真的弄乱了optparse之类的东西,但看不到我的破折号。

Is there something I need to tell sys to give me a normal looking argv? 我需要告诉sys给我一个正常外观的argv吗?

Thanks in advance! 提前致谢!

Somehow, you are not typing a hyphen, but an actual dash character (option -), Unicode 8211, whose UTF-8 representation is the three-byte string \\xe2\\x80\\x93 . 某种程度上,您不是键入连字符,而是键入实际的破折号字符(选项-)Unicode 8211,其UTF-8表示形式是三字节字符串\\xe2\\x80\\x93 We always refer to the character that precedes command-line options as a "dash", but it's really a hyphen! 我们始终将命令行选项之前的字符称为“破折号”,但这实际上是连字符!

Are you copy pasting this? 您要复制粘贴吗? I just took the first two dashes from 我只是拿了前两个破折号

Which gives me this when I call it with -d: ./deleteme.py –d /Library/Python/2.6/site-packages

python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> '–'
'\xe2\x80\x93'
>>> '-'
'-'
>>> 

Did this come from a word doc or pdf or something? 这是来自doc或pdf之类的词吗? Retype it and you should be fine. 重新输入它,你应该没问题。

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

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