简体   繁体   English

从 python 运行 shell 打开文件

[英]Run shell from python to open a file

Trying to open a file using shell:尝试使用 shell 打开文件:

os.system("G:\Folder\2. Cntry\ACCD.accdb")

throw the following error:抛出以下错误:

'G:\Folder.' is not recognized as an internal or external command,

operable program or batch file.可运行的程序或批处理文件。

However when I paste "G:\Folder\2. Cntry\ACCD.accdb" into cmd prompt, it does open the file.但是,当我将"G:\Folder\2. Cntry\ACCD.accdb"到 cmd 提示符中时,它确实打开了文件。

It seems that \2 is read as a似乎\2被读作 . .

but using:但使用:

os.system(r"G:\Folder\2. Cntry\ACCD.accdb")

returns:返回:

'G:\Folder\2.' is not recognized as an internal or external command,
operable program or batch file.

How can I do?我能怎么做?

As the backslash is an escape character in Python, you could:由于反斜杠是 Python 中的转义字符,您可以:

  • Use an raw string: r"G:\Folder\2. Cntry\ACCD.accdb"使用原始字符串: r"G:\Folder\2. Cntry\ACCD.accdb"
  • Use forward slashes: "G:/Folder/2. Cntry/ACCD.accdb"使用正斜杠: "G:/Folder/2. Cntry/ACCD.accdb"
  • Escape the backslashes: "G:\\Folder\\2. Cntry\\ACCD.accdb"转义反斜杠: "G:\\Folder\\2. Cntry\\ACCD.accdb"

Which works for any subprocess function.它适用于任何子进程subprocess

Using os.system you need to pass the path additionally surrounded with single quotes:使用os.system您需要传递另外用单引号括起来的路径:

import os
import subprocess

paths = (
    [r"C:\Temp\2. Cntry\executer.exe", r'"C:\Temp\2. Cntry\executer.exe"'],
    ["C:/Temp/2. Cntry/executer.exe", '"C:/Temp/2. Cntry/executer.exe"'],
    ["C:\\Temp\\2. Cntry\\executer.exe", '"C://Temp//2. Cntry//executer.exe"'],
)

for p1, p2 in paths:
    subprocess.call(p1)
    os.system(p2)

Out:出去:

Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done
Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done

for your prompt, try to open change the path like this because the space causes the pb.对于您的提示,请尝试像这样打开更改路径,因为空间会导致 pb。

G:\Folder\"2. Cntry"\ACCD.accdb

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

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