1
$\begingroup$

I have Python installed and running properly. I have a file called test.py with contents

c = 5

When I go to the file's directory and type import test followed by test.c at the Python prompt in Bash, it returns 5, as expected. When in Wolfram|One I execute ExternalEvaluate["Python", "1+2"], it returns 3. So far, so good. But when I set the directory to the file's directory and execute

s = StartExternalSession["Python"];
ExternalEvaluate[s, "import test"];
ExternalEvaluate[s, "test.c"]

it yields a Failure with tag "EvaluationFailure" and message "Exception Thrown: AttributeError". Inspection of the InputForm of the Failure reveals the line "AttributeError: module 'test' has no attribute 'c'".

What am I doing wrong?

$\endgroup$

1 Answer 1

2
$\begingroup$

After some sleuthing around the internet, I found the problem. The current working directory is not added to Python's path variable. So you have to do this:

s = StartExternalSession["Python"];
ExternalEvaluate[s, "sys.path.insert(1, '')"];
ExternalEvaluate[s, "import test"];
ExternalEvaluate[s, "test.c"]

the second line of which adds the current directory to the path. On my system, using sys.path.append('') in place of sys.path.insert(1, '') didn't work, apparently because there was another test module somewhere else in the path. I read in a few places a recommendation to use sys.path.insert(1, '') rather than sys.path.insert(0, '').

$\endgroup$
3
  • $\begingroup$ Fantastic! This has just saved me... $\endgroup$
    – wilsnunn
    Commented Jan 8, 2019 at 10:08
  • $\begingroup$ @wilsnunn Glad to have been of service, sir/madam. $\endgroup$ Commented Jan 9, 2019 at 16:08
  • $\begingroup$ Hmm. I have the same problem. I cannot import from the local directory. I checked with os.getcwd() that the directory is set correctly. Unfortunately adding ExternalEvaluate[s, "sys.path.insert(1, '')"]; does not seem to help. $\endgroup$
    – Kvothe
    Commented Feb 8, 2021 at 20:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.