pipenvcdpipfile

How to run "cd" command in a Pipfile's [script]?


I need to make something like this in a Pipfile:

...
[scripts]
my_script = "cd folder"
...

Solution

  • Using cd actually works. It just does not seem to work because pipenv run spawns a new shell (not the same shell where you run pipenv run), and runs your command/s there. In that separate shell, it will cd to the folder ... then simply exit. In the original shell where you did pipenv run, you would still be in the same folder.

    You can check that it can access the folder correctly:

    StackOverflow$ tree -L 2 .
    .
    ├── Pipfile
    ├── Pipfile.lock
    ├── folder
    │   ├── file1.txt
    │   ├── file2.txt
    │   └── file3.txt
    └── ...
    
    StackOverflow$ cat Pipfile
    ...
    [scripts]
    # To use multiple commands, wrap with `bash -c` 
    # See https://github.com/pypa/pipenv/issues/2038
    my_script = "bash -c 'cd folder && ls'"
    
    StackOverflow$ pipenv run my_script
    file1.txt file2.txt file3.txt
    
    StackOverflow$
    

    The script shortcut spawned a shell that successfully cd-ed into the folder, but in the original shell, you are still in the same directory ("StackOverflow" in this case).

    Now, I don't know what is the intended purpose of creating a shortcut for cd-ing into a folder. I assume that's not the only command for my_script, because doing cd folder would have been simpler than pipenv run my_script.

    If you are going to do some operation/s inside that folder, then I recommend writing a separate script for all your other commands and just use the [scripts] shortcut to call that script.

    StackOverflow$ tree -L 2 .
    .
    ├── Pipfile
    ├── Pipfile.lock
    ├── folder
    │   ├── file1.txt
    │   ├── file2.txt
    │   └── file3.txt
    └── scripts
        └── my_script.sh
    
    StackOverflow$ cat my_script.sh
    #!/bin/bash
    cd folder
    for file in *
    do
        echo "Doing something to $file"
        sleep 3
    done
    echo "Done."
    
    StackOverflow$ cat Pipfile
    ...
    [scripts]
    my_script = "./scripts/my_script.sh"
    
    StackOverflow$ pipenv run my_script
    Doing something to file1.txt
    Doing something to file2.txt
    Doing something to file3.txt
    Done.
    

    The [script] shortcut would still work correctly (i.e. cd into the folder and do things there). It's also better than chaining commands, which has been discussed by the pipenv maintainers as not its intended purpose.