1

(Edit: I made a typo when writing this question: I put quotation mark around "pyparsing" in script. Thanks @dswdsyd)

When running a python script, there's only python standard library on target machine. When a package is needed, I have to install it first. For example, When I tried to install pyparsing and import it:

subprocess.call([sys.executable, "-m", "pip", "install", "pyparsing"])    
import pyparsing

I got error:

ModuleNotFoundError: No module named 'pyparsing'

So how to install and import a package in the same python script?

[Update:] In the second run of the script, the package can be imported. Strange.

4
  • Noap, I still got "ModuleNotFoundError: No module named 'pyparsing'". Commented Oct 30, 2019 at 6:35
  • that is not reproducable , your provided code works just fine Commented Oct 30, 2019 at 6:38
  • Can you catch the stdout and stderr of the subprocess call and provide it? Commented Oct 30, 2019 at 10:29
  • subprocess works fine. Only import doesn't work at the first run. It works in a second run. Commented Oct 30, 2019 at 11:31

2 Answers 2

2

Problem solved by importlib.invalidate_caches(). According to importlib's documentation:

importlib.invalidate_caches()

Invalidate the internal caches of finders stored at sys.meta_path. If a finder implements invalidate_caches() then it will be called to perform the invalidation. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence.

Sign up to request clarification or add additional context in comments.

Comments

1

Essentially you are passing pyparsing as a variable instead of a string, to fix this change pyparsing to "pyparsing"

try this:

import subprocess
import sys
subprocess.call([sys.executable, "-m", "pip", "install", "pyparsing"])    
import pyparsing

1 Comment

Ah my bad, thank you. I indeed put quotation mark around "pyparsing". The same error occur again.

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.