嘿,我正在尝试执行以下命令(使用 psutil.Popen 和 python 2.7):
"C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE" "C:\docs\ת.xlsm"
使用这段代码:
dir = u"C:\\docs"
doc = os.listdir(dir)[0]
full_path = os.path.join(dir, doc)
command = u"\"C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.EXE\" \"{}\"".format(full_path)
process = psutil.Popen(command)
但是我遇到了这个异常:
process = psutil.Popen(command)
File "C:\Python27\lib\site-packages\psutil\__init__.py", line 1370, in __init__
self.__subproc = subprocess.Popen(*args, **kwargs)
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u05ea' in position 102: ordinal not in range(128)
我发现了这个相关问题: subprocess.Popen with a unicode path .但是那里给出的每个答案都不适合我。
使用 subprocess.Popen(command.encode(locale.getpreferredencoding())),抛出以下异常:
Traceback (most recent call last):
File "scanner_watcher.py", line 53, in _execute
self.scanner.execute(path)
File "scanner_watcher.py", line 356, in execute
self._execute(file_path)
File "scanner_watcher.py", line 201, in _execute
self.open_scanner(file_path, file_package)
File "scanner_watcher.py", line 287, in open_scanner
self.scanner_process = psutil.Popen(command.encode(locale.getpreferredencoding()))
File "C:\Python27\lib\encodings\cp1252.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u05ea' in position 102: character maps to <undefined>
使用 path.encode('mbcs') 将所有 Unicode 字符转换为问号。
我不想使用os.startfile,因为我需要在程序上使用不同的命令,然后处理打开的进程(当os.startfile不'允许这样做)。
我发现了这个修改后的 Popen: https://gist.github.com/vaab/2ad7051fc193167f15f85ef573e54eb9但是这段代码没有经过彻底的测试。
是否有在 python 2.7 中通过 Unicode 命令使用 Popen 的正确方法?
谢谢。
最佳答案
问题是您在定义 command
时使用了双引号。它的编写方式在所有错误的地方将语句拆分为多个字符串。用单引号代替第一个和最后一个引号(字符串的开始和结束)为我解决了这个问题。
command = u'\"C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.EXE\"\"{}\"'.format(完整路径)
关于python - 如何在 Python 2 上使用 psutil.Popen 和 unicode 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46080142/