Skip to main content
 首页 » 编程设计

python子进程给出类型错误

2025年05月04日7zhujiabin

我正在使用 python 2.7

cmd = "sudo start service/newservice db=temp" 
p = subprocess.Popen(shlex.split(cmd), stderr=subprocess.STDOUT) 

以上命令运行良好,并生成了预期的进程。

cmd = "sudo stop service/newservice db=temp" 
p = subprocess.Popen(shlex.split(cmd), stderr=subprocess.STDOUT) 

调用上面时在同一个文件中。它给出了错误。

traceback (most recent call last): 
      File "<stdin>", line 1, in <module> 
      File "/usr/lib/python2.7/subprocess.py", line 672, in __init__ 
        errread, errwrite) 
      File "/usr/lib/python2.7/subprocess.py", line 1213, in _execute_child 
        raise child_exception 
    TypeError: must be encoded string without NULL bytes, not str 

请您参考如下方法:

我解决了。在将它传递给 shlex.split 之前,我只将 cmd 转换为 str,这非常好,尤其是当您以这种方式接收到一些输入时:

cmd = "sudo stop service/newservice db=" + db 

更安全的做法是无论如何都将其转换为字符串。