Working with Command Prompt in Python using Subprocess module - python

In my script, I need to bring up the command prompt which I have not had any issues in creating:
subprocess.Popen([r"cmd.exe"])
That is essentially what I have done so far. I have some arguments that want to be placed in this prompt, that I want automatically ran when I run the script.
What I would like to do is change my directory in the prompt using only Python. Would anybody have any idea how to get there?

subprocess.Popen takes a keyword argument to specify the current working directory. Simply do this:
subprocess.Popen(r"cmd.exe", cwd = "my/lovely/directory/", "more-args")

Well I have no idea about subprocess, but you could use the os module to change directories, start command prompt, run a batch program, etc.
import os
os.chdir('blah')
os.system('start something.bat')
Depends on if you strictly need to use subprocess. Hope that helps though!

Related

How can I execute multiple cmd commands using Python code

Hello I am having this problem where i want to automatically check the system32 file folder with the sfc cmd commands like sfc /verifyonly but the problem is that I can execute only one line in the cmd but I need to execute two and don't know how to execute a second one
import os
os.system("start /B start cmd.exe #cmd /k sfc")
I need another command for sfc /verifyonly so the program would work fully automatic can somebody help with anything pls
I tried a lot of things but nothing seemed to work for me or i am just really stupid and can't find the exact command i should be using
If you look at the docs for os.system they mention the subprocess module as being a more recent development within python that supports multiple systems level processes

Python Subprocess Popen Prepare Python Path under Linux

I am trying to prepare my pythonpath under Ubuntu via subprocess.Popen call, for another script. The call to Python estimateskeleton.py does work fine. However since it needs the python path to be prepared it doesn't work completely correct, since it can not find some other scripts which need to be imported. The export PYTHONPATH command did work with commands.getoutput. However with commands.getoutput the estimateskeleton script still doesn't work / can't find the other files which should be imported. My try to export PYTHONPATH via subprocess.Popen resulted in Error Number 2:
OSError: [Errno 2] No such file or directory
I couldn't find a proper solution with the search function. So I am hoping that one of the more advanced users of this board can help me
Best Regards
import subprocess as sub
import os
import commands
proc = sub.Popen(["export", "PYTHONPATH=\"${PYTHONPATH}:/media/sf_myFolder/Scripts/code/\""],
stdout=sub.PIPE,
stderr=sub.STDOUT)
print proc.communicate()[0]
proc2 = sub.Popen(["python", "estimateskeleton.py"],
stdout=sub.PIPE,
stderr=sub.STDOUT)
print proc2.communicate()[0]
your first Popen command would work without shell=True because export is a shell built-in.
However, that won't fix it, because the second process spawned by Popen is unaware of the previous variable set in a dead process.
So instead of running the first useless Popen, you could add your path to existing PYTHONPATH using os.putenv() like this:
os.putenv("PYTHONPATH",os.pathsep.join([os.getenv("PYTHONPATH",""),"/media/sf_myFolder/Scripts/code"]))
so your next python command is run with the added folder in PYTHONPATH

Pass arguments to executable in Python

I am using os.startfile('C:\\test\\sample.exe') to launch the application. I don't want to know the application’s exit status and I just want to launch the exe.
I need to pass the argument to that exe like 'C:\\test\\sample.exe' -color
Please suggest a method to run this in Python.
You should use the subprocess module instead of os.startfile or os.system in every case that I'm aware of.
import subprocess
subprocess.Popen([r'C:\test\sample.exe', '-color'])
You could, as #Hackaholic suggests in the comments, do
import os
os.system(r'C:\test\sample.exe -color')
But this is no simpler, and the docs for os recommend the use of subprocess instead.
Create a batch file sam_ple.bat with the following commands and arguments
cd C:\test\
start sample.exe -color
Then put sam_ple.bat in the same directory as your script.py file
Enter the following line of code in python to launch the exe:
os.startfile('.\sam_ple.bat')

how to enter in to a folder through python code on linux

I am working on python(scrapy), i am trying to enter in to a folder by using os module but unable to do it, below is what i have tried
import os
scrapepath = "cd /home/local/username/project/scrapy/modulename"
os.system(scrapecmd)
Result:
0
Finally my intention is to enter in to a folder(Destination) from some where (for example home in linux) through python code as i mentioned above. Here actually i am generating some part of the path above dynamically and after that i should enter in to that path and run some commands from inside that folder
Can any one please let me know how to enter to a folder by using python code in linux as above.
To change the current working directory:
os.chdir("/home/local/username/project/scrapy/modulename")
You might also like to simply add that module to python's path (which is where import looks):
sys.path.append("/home/local/username/project/scrapy/modulename")
Use os.chdir:
import os
os.chdir("/home/local/username/project/scrapy/modulename")
AFAIK, os.system() executes the string command in a subshell. So, when you execute something like:
os.system("cd /path/to/directory/")
The cd command will actually be executed in a subshell. But, as the subshell exits after os.system execution, your cd has no practical effect for your application.
see http://docs.python.org/library/os.html
import os
os.chdir(path)

How do I run a function in a Python module using only the Windows command line?

To clarify, the Python module I'm writing is a self-written .py file (named converter), not one that comes standard with the Python libraries.
Anyways, I want to somehow overload my function such that typing in
converter file_name
will send the file's name to
def converter(file_name):
# do something
I've been extensively searching through Google and StackOverflow, but can't find anything that doesn't require the use of special characters like $ or command line options like -c. Does anyone know how to do this?
You can use something like PyInstaller to create a exe out of your py-file.
To use the argument in python:
import sys
if __name__ == "__main__":
converter(sys.argv[1])
You can type in the windows shell:
python converter.py file_name.txt
to give the arguments to the sys.argv list within python. So to access them:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name.txt
at the bottom of the file you want to run, add:
if __name__ == "__main__":
converter(sys.argv[1])
To have a second argument:
python converter.py file_name1.txt file_name2.txt
This will be the result:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name1.txt
sys.argv[2] # this will be file_name2.txt
I would recommend using something like the builtin argparse (for 2.7/3.2+) or argparse on pypi (for 2.3+) if you're doing many complicated command line options.
Only way I can think of is to create a batch file of the same name and within it, call your python script with the parameters provided.
With batch files you don't have to specify the extension (.bat) so it gets you closer to where you want to be.
Also, without any compiling .py to .exe, you may make your script 'executable', so that if you issue command line like myscript param param, the system will search for myscript.py and run it for you, as if it was an .exe or .bat file.
In order to achieve this, configure the machine where you plan to run your script:
Make sure you have file associations set (.py to python interpreter, that is, if you doubleclick at your script in the explorer -- it gets executed). Normally this gets configured by the Python installer.
Edit the COMSPEC environment variable (look inside My Computer properties) to include .PY extension as well as .EXE, .COM, etc.
Start a fresh cmd.exe from Start menu to use the new value of variable. Old instances of any programs will see only old value.
This setup could be handy if you run many scripts on the same machine, and not so handy if you spread you scripts to many machines. In the latter case you better use py2exe converter to bundle up your application into a self-sufficient package (which doesn't require even python to be installed).

Categories

Resources