Problem using os.system() with sed command

后端 未结 7 2182
耶瑟儿~
耶瑟儿~ 2020-12-20 04:30

I\'m writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.

I\'m hav

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 04:47

    So from previous answers we now know that id is a Unicode string, which makes cmd1 a Unicode string, which os.system() is converting to a byte string for execution in the default encoding.

    a) I suggest using subprocess rather than os.system()

    b) I suggest not using the name of a built-in function as a variable (id).

    c) I suggest explicitly encoding the string to a byte string before executing:

    if isinstance(cmd,unicode):
        cmd = cmd.encode("UTF-8")
    

    d) For Lennart Regebro's suggestion add:

    assert type(cmd1) == type(cmd2)
    

    after

    print cmd1 == cmd2
    

提交回复
热议问题