简体   繁体   English

Python:如何在windows中的env变量中处理unicode

[英]Python: How to handle unicode in env variable in windows

I want to pass my custom environment variables for the location of my existing application log file directory location in in newly spawn process, Now the problem is that user directory path may contain unicode, depends on user's locale (It can be latin-1) 我想在新生成的进程中将我的自定义环境变量传递给我现有应用程序日志文件目录位置的位置,现在的问题是用户目录路径可能包含unicode,取决于用户的语言环境(可以是latin-1)

# This Works fine if all the characters are ascii
self.app_log_dir = u'C:\\USERS_CUSTOM_PATCH\\logs\\'

env['APP_LOG_DIR'] = self.app_log_dir 

    p = Popen(
                    cmd, close_fds=False, env=env, stdout=stdout.fileno(),
                    stderr=stderr.fileno(), stdin=stdin.fileno(),
                    creationflags=(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
                )

p.start()

##############################

# But path like this fails
self.app_log_dir = u'C:\\USERS_CUSTOM_PATCH\\xx_ÔÔ_xx\\logs\\'
...
...
p.start()

Below is the Exception I received from above non-ascii path with popen, 以下是我从popen上面的非ascii路径收到的异常,

Exception: environment can only contain strings 例外:环境只能包含字符串

Can anyone suggest work around as I need to handle non-ascii paths in my application? 任何人都可以建议解决,因为我需要在我的应用程序中处理非ascii路径?

Updated: 更新:

pp_log_dir variable is configurable by user, I am unit testing my code and found the issue as user can provide any path in config.py file pp_log_dir变量可由用户配置,我是单元测试我的代码并发现问题,因为用户可以在config.py文件中提供任何路径

如果用户提供unicode路径,请将其编码为相关编码。

env['APP_LOG_DIR'] = self.app_log_dir.encode('latin-1')

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

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