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
$\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$
  • $\begingroup$ Fantastic! This has just saved me... $\endgroup$ – wilsnunn Jan 8 at 10:08
  • $\begingroup$ @wilsnunn Glad to have been of service, sir/madam. $\endgroup$ – CarbonFlambe Jan 9 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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