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.
Related
recently, I want to use python script to set environment in linux.This is one line of my code:
p = subprocess.call(['/bin/csh', '-c', "source setup.csh"])
My setup.csh file is below:
add questa10.2b
add ds5-2013.06
setenv MODELSIM modelsim.ini
But when I run my python, it shows that the files have sourced on screen, but it turns out I have to type myself on command line.
How could I solve these problem? Can any one please help me with this?
You're creating a new csh shell as a subprocess and then running your commands inside that shell, which then terminates. The commands do not run in, or affect, the parent shell within which Python is running. When you just run the commands yourself, they affect the current shell.
If you need these settings to persist in your current shell after Python terminates, your best bet in general is to source setup.csh rather than putting it in a Python script. If other child processes of the Python script need your environment variables, you can alter os.environ.
I am new to Python, could someone please let me know if we can register our python script to work as one of the command of cmd.exe, I am not asking about parsing or accepting command line arguements using argparse, etc..
Lets say I have a SearchDir.py file, to run it from cmd prompt I have to do "python SearchDir.py", so is there any way to simply do "SearchDir" and it should act as one of the command of cmd.exe
Yes, it is possible (if I have understood you correctly. The question was a bit unclear)
The first thing you need to do is to add a shebang to the top of your script: https://en.wikipedia.org/wiki/Shebang_(Unix). I see you mentioned cmd.exe so I assume you need this to work on Windows? In that case you should read https://docs.python.org/3/using/windows.html#shebang-lines as well
On unix hosts, the second thing we need to do is set our file as executable with chmod +x <filename>. I try to stay away from Windows, but from what I remember this is not relevant on Windows.
Last you need to place the script in a folder referenced by your $PATH-variable
The script will now be accessible as SearchDir.py from cmd.exe or a unix shell. If you want to omit the ".py"-part you simply rename the file to just "SearchDir"
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.
I want to write a python program that runs in the background.
I mean, like we install Python package. And later, we can run any script using python in front of the script name. This means that some python process is running in background which can take inputs and perform actions.
And in case of linux, you can call grep from anywhere. That means grep is also running in the background somehow.
I want to write something like that in python. When I call certain function with name and arguments at any time, it should perform the intended action without caring for the original code. But I am not able to find how to achieve that.
Can anyone please help me here?
Thanks in advance.
Clarification: the fact that you can run python or grep in a console just by typing their name, does not mean that they run in background. It means that there exist an executable file in some location, and this location is listed in the environment variable PATH.
For example, on my system I can run Python by typing python. The python executable is installed at /usr/local/bin/python, and has the execute permission bit on.
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
and yes, /usr/local/bin is contained in PATH.
You can do the same with python scripts:
ensure that the very first line of your script contains #!/usr/bin/python or #!/usr/bin/env python
give your script execute permissions: chmod a+x yourScript
either move your script to one of the directories contained in $PATH, or add the directory where your script is located to PATH: export PATH=$PATH:/home/you/scripts
Have a look at
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
you can roll out your own daemon by inheriting the Daemon class and overriding run method
from daemon import Daemon
class run_daemon(Daemon):
def run(self):
import sys
run_daemon.execute_shell_command(sys.argv[1])
#staticmethod
def execute_shell_command(ShellCommand):
import subprocess
process = subprocess.Popen(ShellCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.communicate()
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.