5

I really like the ability of jupyter to mix bash commands inline like this:

for d in list_of_dirs:
    ! ls {d}

However, is there any way to get the output of one of these inline commands to be assigned to a python variable? For example as a python list?

3 Answers 3

5

Something like this?

Code:

python_list = []
for d in list_of_dirs:
    temp_list = !ls {d}
    python_list.extend(temp_list)
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! I feel stupid now for not trying to just directly assign it to a variable. Thanks!! Will accept this when it allows.
It's Python! Use pseudo-code if you are not sure!))
4

This works well

for d in list_of_dirs:
    out = !'ls {0}'.format('d')

Comments

1

os.popen works for this. popen - opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read. split('\n') converts the output to list

import os
list_of_ls = os.popen("ls").read().split('\n')
print list_of_ls

1 Comment

hmm interesting alternative, thank you. If it turns out that assigning ! output to a variable directly isn't possible I'll select this answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.