Home > Net >  Translating Bash to Python
Translating Bash to Python

Time:01-03

I am trying to translate this from Bash to Python:

password=$(func_name "${configFile}" "<password" "2")

func_name and configFile have been defined earlier in the script. func_name is a function and configFile is a working directory leading to an XML file.

But I don’t know what to do with func_name in this case. And is password and array here?

Knowing that an array in Bash is called a list in Python, I have tried this, but I am not sure:

password = [configFile, "<password", "2"]

Is this correct?

CodePudding user response:

A rough translation would be:

password = func_name(configFile, "<password ", "2")

But this won't necessarily work at all. Python and bash think in fundamentally different ways, and you can't really "translate" back and forth between them; you have to think differently in the two languages.

For example, bash functions don't really have return values. They can print output as they run (the output being a sequence of bytes), and return a status code (basically, whether the function succeeded or not). The bash code you have captures the output (what the function prints), treats it as a string, and stores it in the password variable.

Python functions return objects. bash has no concept of an object. Python objects can be strings... or any of a variety of built-in object types, or any type you import from a library or define yourself. My Python code here takes whatever object the function returns, and stores it in the password variable. BTW, Python functions don't have return statuses, instead they can throw errors (which is a concept bash doesn't have).

Similarly, the arguments you pass to a bash function are all strings, but in Python they're objects (which can be strings, but can also be completely different types of things).

I would strongly recommend learning the languages you're trying to use. You can't translate between them at the syntactic level, you need to translate at the conceptual level, and to do that you need to understand both languages at that level.

  • Related