Winger Sendon Winger Sendon - 1 year ago 104
Python Question

Writing a line to CMD in python

I am very new to Python and I have been trying to find a way to write in cmd with python.

I tried

too. But I am not sure how to use subprocess.

While using os.system(), I got an error saying that the file specified cannot be found.
This is what I am trying to write in cmd
os.system('cd '+path+'tesseract '+'a.png out')

I have tried searching Google but still I don't understand how to use subprocess.

It's not a problem with python anymore, I have figured out. Here is my code now.

os.system("cd C:\\Users\\User\\Desktop\\Folder\\data\\")

os.system("tesseract a.png out")

Now it says the file cannot be open. But if I open the cmd separately and write the above code, it successfully creates a file in the folder\data.

Answer Source

Each call to os.system is a separate instance of the shell. The cd you issued only had effect in the first instance of the shell. The second call to os.system was a new shell instance that started in the Python program's current working directory, which was not affected by the first cd invocation.

Some ways to do what you want:

1 -- put all the relevant commands in a single bash file and execute that via os.system

2 -- skip the cd call; just invoke your tesseract command using a full path to the file

3 -- change the directory for the Python program as a whole using os.chdir but this is probably not the right way -- your Python program as a whole (especially if running in a web app framework like Django or web2py) may have strong feelings about the current working directory.

The main takeaway is, os.system calls don't change the execution environment of the current Python program. It's equivalent to what would happen if you created a sub-shell at the command line, issued one command then exited. Some commands (like creating files or directories) have permanent effect. Others (like changing directories or setting environment variables) don't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download