0

I want to use subprocess in kaggle notebook, kaggle notebook is very similar to jupyter notebook.

When I use the following code I got 0.

import subprocess
subprocess.call("ls")

What I want is the list of the files in current folder.

Could you help me please?

jww
  • 97,681
  • 90
  • 411
  • 885
  • 2
    That is the return code of the command and the expected result. There are other functions in the `subprocess` module that will return other information. Also consider using `os.listdir(path)` instead. – Klaus D. Oct 21 '19 at 07:26
  • Thanks for your replies.But I want to perform other linux commands...for example,git command in notebook.So I want such a python package to help me. –  Oct 21 '19 at 07:35

1 Answers1

0

You can use this code. I can't explain it because I don't know what know anything about the subprocess library but it worked from my jupyter notebook when I tried it. I figured it out from this stackoverflow thread. However, I couldn't get it to work when I did something like "ls -a".

import subprocess

process = subprocess.Popen('ls',
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)


with process.stdout:
    for line in iter(process.stdout.readline, b''):
        print(line.decode().strip())

A Better Alternative if the Kaggle notebook has the same functionality as Jupyter notebook.

In Jupyter notebooks, you can execute commands by prepending ! before the command in a jupyter notebook cell. For example, you can clone a github repo from the cell with this command !git clone https_repo_here. In my subprocess example above, I couldn't get ls -a to work but I can get it to work just by using !ls -a in the Jupyter notebook cell.

Another helpful tip in Jupyter notebook is %. I don't know all the functionality of this thing (I think it's called a magic symbol) but I know that you can, for example, change the working directory of you notebook just by writing %cd different_directory_here. I don't know why but if you wrote !cd different_directory_here, it won't permanently change the working directory of your Jupyter notebook.

zipline86
  • 561
  • 2
  • 7
  • 21