Writing a line to CMD in python - python

I am very new to Python and I have been trying to find a way to write in cmd with python.
I tried os.system and subprocess 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.
EDIT:
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.

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.

Related

Issue with executing php through cmd from python

I will try to be brief!
For whatever reason, I couldn't make the entirety of my program in python, so I had to outsource one specific task to php (a language I do not know very well). As the python program runs, it is supposed to trigger the php program to run, and then do a few things afterwards which is not a problem.
It seems to me that, to be able to run something through python, you need it to be able to run through cmd first, and then you can make python use cmd to run the program. I had a few issues there, because the programs are on different drives, and the php program references other files and locations in the same directory and in sub-directories to where it is, this means I couldn't execute in one line of cmd, but first had to change directory, to then execute the php program from the folder it's in. Because my command wasn't just one line, I made a batch file containing all the steps.
My current working method is to open up cmd, change directory in cmd to where the php file is, and then run the php file. I had to add php to the "Environment Variable Path" to be able to do this. Here is the batch file that currently works when run by me:
cd /d C:
cd C:\Users\UserMain\Desktop\php\colorextract
php (2).php
When I double click this bat file, from my E drive, it successfully executes the php program. But when I tell python to execute the batch file, that is where things go wrong.
Here is my python code, apologies for the name of the bat file:
import os
os.system('cmd /k "bitch.bat"')
The resultant cmd window then goes thru the steps of the batch file: 1) it changes to the right directory, 2) it is unable to execute the php file because:
'php' is not recognised as an internal or external command, operable program or batch file.
Now, this is the standard error you get if you were to try running a php program without having added php to the "Environment Variable Path", I know this because I went through that same thing. But if I manually open a cmd window, not administrative or anything, I can 1) successfully perform the steps outlined in batch file, and program runs, and 2) I can even run the bat file, and that also runs the program.
The cmd window opened by python does not seem to be able to reference the "Environment Variable Path", or it is for another reason somehow handicapped against being able to do all the things that a normal cmd widow can. How can this be fixed?
Thanks in advance to anyone who reads this!
Edit: I found that python had not detected the changes I made to the environment variables the day before, hence why python's cmd was giving the exact error that not having php in the environment variable gives. After I restarted my computer, my code worked. Thank you to #Gerhard and #Aaron Junker for making me think much harder about this issue.
so I found a command that can be run after importing os.
print(os.environ)
I ran this, and it told me that Python could not see that php had been added to the environment variables, well, more likely that python did not have the most up to date information regarding what was in the path variable(s).
Restarting my computer made the changes kick in, and now my original code works. Whilst I do feel very stupid, I'm just happy that this is resolved.
This seems to me like both instances use different environment variables.
Open
System Properties -> Advanced -> environment variables and look that PHP is in the PATH variable in user variables and in System variables.

python shell script execution that passes environment to the parent

So I know how subprocess works and use it a lot, but I've run into a strange issue. I need to execute an export of some environment variables. The reason is that some program (black-box) executes a program that seems like it runs in a subshell, so it doesn't have access to the environment variables but it has access to all my files.
I can't hard code the environment variables so I want to source or . the file that has the export commands in it. However, if I source or . that file in a subprocess, it won't make any difference to its parent process. In which case I either need some function besides subprocess that can execute shell commands without creating a subprocess, if that exists. Another issue is that a subprocess doesn't have the proper permissions to read the file.
And copying the environment variables via os isn't really possible either.
Does anything besides subprocess exist? Or is there some other kind of workaround?
IMHO the simplest solution consists in creating a new shell script (let's call it run_black_box.sh) which sources the setup script (let's assume it is named setup.sh) to initialize the environment and then calls the black_box program.
Here is a possible content of run_black_box.sh:
#/bin/bash
source setup.sh
black_box
The you can pass run_black_box.sh to subprocess for execution.

How do i do sub processes properly with Python

I am new to python so I'm in the early stages of learning it. I was wondering if anyone knows how to run a system command after another. It's hard to explain:
subprocess.call('dir',shell=True)
subprocess.call('cd ..',shell=True)
subprocess.call('dir',shell=True)
When I run the command I expect to see the directory which the file is run. Which was fine.
Then the second process I expect to go up a directory.
Then the third command I expected to see the higher directory. Which I didn't I just saw the first directory.
Could some one explain why it isn't working as I expected and what I should do to correct it.
The general rule is that children cannot affect the parent's environment.
subprocess.call creates a child process. The child process can do many things. But, any changes it makes to the current working directory or to environment variables only last for the duration of the subprocess call. After the call completes and control returns to the parent, the parent's environment is restored unchanged.
If you want the cd to affect the next dir command, you need to have both in the same child. For example:
subprocess.call('cd ..; dir', shell=True)
You probably asked this question for more general purposes. But, for the specific examples that you provided, note that those actions might be better performed with the os module, rather than the subprocess module: listing files in the current directory can be done with os.listdir and changing the current working directory can be done with os.chdir
If you are trying to change the working directory in python that can be accomplished simply by os module. You can find that documentation here. I would suggest only using subprocess.call to call a script or another program that isn't trying to modify stuff based on the current environment.
When you run a subprocess with shell=True, python starts up a new shell to run the command in. It is basically the same as if python start up a new command prompt, entered in the command, and then closed the command prompt.
The consequence is that any action which only affects the shell is lost when the shell is closed. So you can create files and you'll see that because the hard drive is changed. But if you change the current directory of the shell that change will be lost.
You might wonder about the output of the program. Basically, the default is for the output of the program to be copied to the output of the calling program. (You can override this.)
If you want to change the current directory you want os.chdir. In general, you should avoid calling subprocesses and prefer python's tools. For example, instead of dir use os.listdir.

How to use cmd from python

Im trying to use python to run cmd.exe and thereby running commands like cd C:\name..... and executing other programs from the cmd what I have so far is.
os.system("cmd.exe").
os.system("cd C:\name\first\second").
When I try to run three other commands a new cmd window replaces the old one and the commands dont work since they need to be consecutively after each other.I already tried the above code and need help running the next three. Also can you explain what suproccess are.
See my answer to this recent question for why os.system("cd WHEREVER") does not do what you expect.
Briefly, when you run os.system('cd WHEREVER') you are creating a new command shell which has its own idea of the current directory. This change in the current directory will be entirely "forgotten" on subsequent calls to os.system(). You need to change the current directory in the parent process (the script) with os.chdir('WHEREVER') in order to retain the change for subsequent os.system() calls.

Executing some simple command in Command prompt using Python

I need to execute the simple command below in windows 7 command prompt using Python26.
cd C:\Python26\main project files\Process
C:\Aster\runtime\waster Analysis.comm
It runs a FEM simulation and I tried it manually and it worked well. Now, I want to automate the write procedure using Python26.
I studied the other questions and found that the os.system works but it didn't. Also I saw subprocess module but it didn't work.
The current directory is a process property: Every single process has its own current directory. A line like
os.system("cd xyz")
starts a command interpreter (cmd.exe on Windows 7) and execute the cd command in this subprocess, not affecting the calling process in any way. To change the directory of the calling process, you can use os.chdir() or the cwd keyword parameter to subprocess.Popen().
Example code:
p = subproces.Popen(["C:/Aster/runtime/waster", "Analysis.comm"],
cwd="C:/Python26/main project files/Process")
p.wait()
(Side notes: Use forward slashes in path names in Python files. You should avoid os.system() and passing shell=True to the function in the subprocess module unless really necessary.)

Categories