Search code examples
pythonlinuxpython-3.xsubprocesspopen

python subprocess popen set home directory as cwd


I have a small problem. I'm on a ubuntu 16.04 machine and in a python script I want to start a subprocess which should start in the home directory of the user. I tried it with:

subprocess.Popen('echo "Test"', cwd="~", shell=True,universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash")

but when I do this I get the following error:

 proc = subprocess.Popen('echo "test"', cwd="~", shell=True,universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash")
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '~'

I'm not sure what I did wrong since when you enter ~ in a cd command it cds you to the home directory. I hope someone has a solution why it is not working this way and what would be the right way to start it in the home directory.


Solution

  • I've simplified your code for clarity.


    With Python 3.6 or higher you can do the following:

    import subprocess, pathlib
    subprocess.Popen(['echo',  'test'], cwd=pathlib.Path.home())
    

    With Python 3.5 you need to wrap Path.home() into str():

    import subprocess, pathlib
    subprocess.Popen(['echo',  'test'], cwd=str(pathlib.Path.home()))
    

    With any Python version below 3.5 you can use:

    import os, subprocess
    subprocess.Popen(['echo',  'test'], cwd=os.path.expanduser('~'))