Subprocess changing directory
What your code tries to do is call a program named cd ..
. What you want is call a command named cd
.
But cd
is a shell internal. So you can only call it as
subprocess.call('cd ..', shell=True) # pointless code! See text below.
But it is pointless to do so. As no process can change another process's working directory (again, at least on a UNIX-like OS, but as well on Windows), this call will have the subshell change its dir and exit immediately.
What you want can be achieved with os.chdir()
or with the subprocess
named parameter cwd
which changes the working directory immediately before executing a subprocess.
For example, to execute ls
in the root directory, you either can do
wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)
or simply
subprocess.Popen("ls", cwd="/")
Python - Change working directory in subprocess.call syntax
I'm suspecting that if the ./
isn't passed to subprocess
, on some systems the command may not be found (security issues, .
not in system path)
The other issue could be a wrong directory/command not really in the directory.
Obviously I couldn't test that, but that's a safe way (and with error checking) to execute a command in a directory, so it should fix your issue, or at least pinpoint a path problem:
command_dir = '/path/to/sh_script_dir'
command_file = os.path.join(command_dir,"script_name.sh")
if not os.path.isfile(command_file):
raise Exception("{}: no such file".format(command_file))
subprocess.call([command_file,var1,var2], cwd = command_dir)
- compose your command file with the full path (stored in a variable)
- test this full path existence prior to running your command (helps to track down a path error)
- don't use
shlex.split
when you can pass the list of arguments instead
How can I specify working directory for popen
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
Python 3: subprocess, changing directory
I have discovered the answer with some help from various stackoverflow posts on the topic as well as stumbling through possible solutions. It was not easy!
self.relativePath = os.path.dirname(sys.argv[0])
self.relativePath1 = self.relativePath + '\\your_subdirectoryHERE\\'
Be sure to include double slashes, to match os.path.dirname(sys.argv[0])
self.process = subprocess.Popen(self.relativePath1 + 'flare.exe -command', cwd=self.relativePath1)
How to change directory and run further command in that directory using python?
you can use &&
instead pipe |
. so, in this case, will git status
will only work if cd /some_directory
worked. &&
means to execute the next command if the previous exited with status 0. Change the path according to your OS and directory.
| : The pipe operator, it passes the output of one command as input to
another. A command built from the pipe operator is called a pipeline.
what-are-the-shells-control-and-redirection-operators
import os
os.system(r"cd /home/code/ && ls && git status")
How to run shell commands in different directory using python subprocess command?
The subprocess
methods all accept a cwd
keyword argument.
import subprocess
d = subprocess.check_output(
['ls'], cwd='/home/you/Desktop')
Obviously, replace /home/you/Desktop
with the actual directory you want.
Most well-written shell commands will not require you to run them in any particular directory, but if that's what you want, this is how you do it.
If this doesn't solve your problem, please update your question to include the actual code which doesn't behave like you expect.
(Of course, a subprocess is a really poor way to get a directory listing, and ls
is a really poor way to get a directory listing if you really want to use a subprocess. Probably try os.listdir('/home/you/Desktop')
if that's what you actually want. But I'm guessing you are just providing ls
as an example of an external command.)
Related Topics
How to Add Property to a Class Dynamically
What's the Purpose of "Send" Function on Python Generators
How to Get User Ip Address in Django
Importerror: No Module Named 'Encodings'
How to Implement an Ordered, Default Dict
Calling a Python Script with Input Within a Python Script Using Subprocess
How to Convert String to Binary
How to Find an Element That Contains Specific Text in Selenium Webdriver (Python)
How to Use a Dll File from Python
How to Use Stringio in Python3
Python List VS. Array - When to Use
How to Time a Code Segment for Testing Performance with Pythons Timeit