2

The goal is to open a particular excel file using a python shell subprocess. The code cannot be more simple yet I cannot figure out what is wrong:

import subprocess
arg1 = "C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.EXE"
arg2 = "C:\\Users\\user\\Documents\\test.xlsm"
p = subprocess.Popen(["start", arg1, arg2], shell=False)

The command works perfectly directly on the shell but when done through subprocess throws the following error: FileNotFoundError: [WinError 2] The system cannot find the file specified

I have also tried the below which works equally fine directly on the shell but the behavior is different: p = subprocess.Popen([arg1, arg2], shell=False)

The following failed assertion pops up from Excel: snapshopt error

My next try was:

import os
os.system("C:\\Users\\user\\Documents\\test.xlsm")

Which replicates the same assertion error as above plus returns a code 3 which based on System Error Codes (0-499) is a path not found.

Again same path works on shell, at this stage I run out of ideas, any help?

2
  • Isnt start as shell command ? So you should probably use shell=True Commented Jun 8, 2020 at 9:24
  • yep shell true throws the assertion error from excel Commented Jun 8, 2020 at 9:32

1 Answer 1

3

os.startfile is actually a better way to do it. As specified in the documentation -

os.startfile(path[, operation])

Start a file with its associated application.

When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories)

You can just do the following -

import os

os.startfile("C:\\Users\\user\\Documents\\test.xlsm")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that but this gives the same assertion error as above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.