Search code examples
pythonoctavegnu

Execute a Python file in GNU Octave


I write a code to run a python file in GNU Octave. This is that code part.

[output,status]=python('customers.py');
output
status

But when execute that code I get an error like this.

'python' is not recognized as an internal or external command,
operable program or batch file.
output =
status =  1

I don't understand why I got an error like this. The python file is also in the same directory. This is the python code:

# Import sys module
import sys

# Total number of arguments
print('Total arguments:', len(sys.argv))

#print("Argument values are:")
# Iterate command-line arguments using for loop
#for i in sys.argv:
  #print(i)

# Define a dictionary
customers = {'9876':'Kamal Perera','9873':'Amal Fernando',
'9865':'Vimal Gunasena','9843':'Chamal Sirisena', '9862':'Dumal Zoysa',
'9831':'Nimal Walpola'}

#print("The customer names are:")
# Print the values of the dictionary
#for customer in customers:
    #print(customers[customer])

# Take customer ID as input to search
print("Search customer ID:",sys.argv[1])
name = sys.argv[1]
# Search the ID in the dictionary
for customer in customers:
    if customer == name:
        print(customers[customer])
        break

How do I solve this issue?


Solution

  • The python command is effectively a wrapper to the system command, which calls the operating system's python command for you.

    If the system's python executable is not on the system PATH, then obviously octave will fail to find it.

    Judging from the error I'm guessing you're on windows? In which case, look up how to add python to your PATH in windows.

    (e.g. here's a random first link from a duckduckgo search: https://datatofish.com/add-python-to-windows-path/ )

    Alternatively, you can use getenv("PATH") to check what your current system path is, and modify it from within octave to concatenate that string with the python executables directory, and then set it using setenv("PATH")

    EDIT (2023): Another (and probably better) option to interface with python is the octave-pythonic package: https://gnu-octave.github.io/packages/pythonic / https://gitlab.com/mtmiller/octave-pythonic