Python - 使用subprocess.call()时Windows路径中的双反斜杠

时间:2015-09-25 09:04:45

标签: python windows python-3.x backslash

我无法使用此代码。

subprocess.call([os.path.normpath(
                   os.path.dirname(
                     os.path.realpath(
                       sys.argv[0]))) + '\mscgen.exe', 
                 '  -T png ' + os.path.normpath(
                                 os.path.dirname(
                                   os.path.realpath(
                                     args.mscInputFilePath)))])

,其中

sys.argv[0] == 'D:/Python/mscFromLog/msgFromLog.py'
args.mscInputFilePath == 'D:\\Python\\mscFromLog\\log_files\\my_file.signalling'

,鉴于我(可能是错误的)使用normpathdirnamerealpath,请展开以下路径:

'D:\\Python\\mscFromLog\\mscgen.exe'
'D:\\Python\\mscFromLog\\log_files'

我怀疑将这些双反斜杠传递给Windows是一个问题。它肯定会窒息

dir D:\\Python\\mscFromLog\\mscgen.exe

请注意,追加.replace('\\\\', '\\')没有帮助。

[WinError 2] The system cannot find the file specified
['Traceback (most recent call last):\n',
'  File "D:/Python/mscFromLog/msgFromLog.py", line 248, in GenerateMsc\n
    subprocess.call([os.path.normpath(os.path.dirname(os.path.realpath(sys.argv[0]))) + \'\\\\mscgen.exe\', \'  -T png \' + os.path.normpath(os.path.dirname(os.path.realpath(args.mscInputFilePath)))])\n',
'  File "D:\\Python\\Interpreter\\lib\\subprocess.py", line 560, in call\n
    with Popen(*popenargs, **kwargs) as p:\n',
'  File "D:\\Python\\Interpreter\\lib\\subprocess.py", line 950, in __init__\n
    restore_signals, start_new_session)\n',
'  File "D:\\Python\\Interpreter\\lib\\subprocess.py", line 1220, in _execute_child\n
    startupinfo)\n',
'  File "D:\\Programs\\PyCharm Community Edition 4.5.4\\helpers\\pydev\\pydev_monkey.py", line 299, in new_CreateProcess\n
    return getattr(_subprocess, original_name)(appName, patch_arg_str_win(commandLine), *args)\n',
'FileNotFoundError: [WinError 2] The system cannot find the file specified\n']

1 个答案:

答案 0 :(得分:2)

在包含分隔的反斜杠的字符串路径上附加.__str__()应该可以解决问题。

例如: args.mscInputFilePath.__str__()

从直觉上讲,该方法为您提供了在某些情况下调用print()时看到的内容,并且是对Windows上偶尔希望存储打印字符串对象的结果的偶尔回答。关于__str____repr__之间的区别,有很多不错的文章,以获取更多背景信息。