I am new to python, and I am converting a C++ file into python, but I was not sure how to translate the following lines of C++ code:
virtual void show() const override
{ system(("cat " + filename).c_str()); }
I am new to python, and I am converting a C++ file into python, but I was not sure how to translate the following lines of C++ code:
virtual void show() const override
{ system(("cat " + filename).c_str()); }
system()
is a function which executes a system command.
Doing this in Python is usually performed with the subprocess module. See this question for more information.
The docs even have a section showing how to replace the system
call:
subprocess.call("cat " + filename, shell=True)
Python does have a function os.system
that's does exactly the same thing as the C function, because it's a thin wrapper around that C function:
This is implemented by calling the Standard C function system(), and has the same limitations.
And you can easily verify in the source that this is true.
But as the docs say, "The subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function."
be sure to import os
"equivalent" to < cstdlib > < stdlib.h > where the function system() is normally implemented.
An exact conversion could looks like:
os.system(str("cat" + filename))
, however if filename is already a string, then just call as:
os.system("cat" + filename)
Also, I am not so familiar with C++, but knowing ANSI C, it seems like virtual void show() is some method or function therefore you might be looking for:
def show(filename):
os.system("cat" + filename)
#notice that i used the filename as parameter,
#however if its a global variable this is unnecessary.
An important advise: it might be implemented inside a class, if the filename variable is "global" or public for methods in this class, then the parameters is not needed.
Good luck!