【问题标题】:Subprocess.run() cannot find file, even if path.exists() returns trueSubprocess.run() 找不到文件,即使 path.exists() 返回 true
【发布时间】:2019-07-22 21:35:21
【问题描述】:

我找到了这两个页面:

Subprocess.run() cannot find path

Python3 Subprocess.run cannot find relative referenced file

但这没有帮助。第一页谈论使用​​\\,但我已经这样做了,第二页谈论围绕其中一个论点的双引号。

work = Path("R:\\Work")
resume = work.joinpath("cover_letter_resume_base.doc")

current_date = construct_current_date()

company_name = gather_user_information(question="Company name: ", 
                                        error_message="Company name cannot be empty")

position = gather_user_information(question="Position: ", 
                                   error_message="Position cannot be empty")

# Construct destination folder string using the company name, job title, and current date
destination = work.joinpath(company_name).joinpath(position).joinpath(current_date)

# Create the destintion folder
os.makedirs(destination, exist_ok=True)

# Construct file name
company_name_position = "{0}_{1}{2}".format(company_name.strip().lower().replace(" ", "_"), 
                                position.strip().lower().replace(" ", "_"), resume.suffix)

resume_with_company_name_job_title = resume.stem.replace("base", company_name_position)
destination_file = destination.joinpath(resume_with_company_name_job_title)

# Copy and rename the resume based on the company and title.
shutil.copy2(src=resume, dst=destination_file)

if destination_file.exists():
    print(f"{destination_file} created.")
    #subprocess.run(["open", str(destination_file)], check=True)

程序从用户那里获取公司名称和职位,生成当前日期,创建目录,然后根据用户输入移动/重命名基本简历。

输出和结果

Company name: Microsoft
Position: Software Eng
R:\Work\Microsoft\Software Engineer\20190722\cover_letter_resume_microsoft_software_eng.doc 
created.

错误信息

[WinError 2] The system cannot find the file specified
Traceback (most recent call last):
  File "c:/Users/Kiska/python/job-application/main.py", line 59, in <module>
    main()
  File "c:/Users/Kiska/python/job-application/main.py", line 53, in main
    raise error
  File "c:/Users/Kiska/python/job-application/main.py", line 48, in main
    subprocess.run(["start", str(destination_file)], check=True)
  File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

if 语句返回Truesubprocess.run() 看不到文件,但我不太确定为什么。

【问题讨论】:

  • 你想要"start"而不是"open"吗?
  • @finefoot @Thomas Weller - 我从这个答案中找到了openstackoverflow.com/a/434612/11781428
  • @finefoot - 查看更新
  • 总是将完整的错误消息(从单词“Traceback”开始)放在有问题的地方(作为文本,而不是屏幕截图)。还有其他有用的信息。
  • @furas - 我的代码被 try/except 块包围,所以上面的错误消息就是我得到的。

标签: python python-3.x windows subprocess


【解决方案1】:

您在哪个操作系统上?路径中的反斜杠表明您使用的是 Windows,并且您正在使用 open 使用其默认应用程序打开文档。但是,查看Open document with default OS application in Python, both in Windows and Mac OS 这个问题,对于 Windows,您应该使用 start 而不是 open

subprocess.run(["start", str(destination_file)], check=True, shell=True)

您还需要添加shell=True 才能使start 工作。但是,您应该事先阅读https://docs.python.org/3/library/subprocess.html#security-considerations

(我怀疑出现了错误 [WinError 2] The system cannot find the file specified,因为 Windows 找不到 open - 这与您尝试打开的文档无关。)

【讨论】:

  • @Kiska 尝试改用os.startfile(destination_file)
  • 绝对使用os.startfile 而不是CMD。启动 cmd.exe 没有意义;冒着 CMD 解析命令行的风险;然后让 CMD 尝试CreateProcessW,然后最终调用ShellExecuteExW。使用os.startfile,我们直接调用ShellExecuteW。但是如果你确实使用shell=True 的子进程,在这种情况下永远不要传递一个列表。在几乎所有情况下,它在 Unix 和 Windows 中都是错误的,无论如何我们都必须构建一个命令行字符串,subprocess.list2cmdline 没有实现 CMD 的引用(好像任何人都可以......它的规则是如此混乱)。
猜你喜欢
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
相关资源
最近更新 更多