0

I trying to write a script but I don't understand the following behavior.

Let's say I have script.py containing

import sys
import subprocess

result = subprocess.run(["flatpak", "list", "--columns=application", "--app"], check=True, stdout=subprocess.PIPE)
somestring = str(result.stdout, 'utf-8')
print(somestring)

And from interactive shell I run :

>>> import script

This works perfectly.

But then, if I have this file instead (called func.py) :

import sys
import subprocess

def GetInstalledApps():
  result = subprocess.run(["flatpak", "list", "--columns=application", "--app"], check=True, stdout=subprocess.PIPE)
  somestring = str(result.stdout, 'utf-8')
  print(somestring)

If I jump into python interactive shell and run

>>> import func # this call succeed
>>> func.GetInstalledApps() # this throw the following error :
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/func.py", line 11, in GetInstalledApps
    somestring = str(result.stdout, 'utf-8')
           ^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: a bytes-like object is required, not 'str'

I understand what the error means, but I don't understand it is thrown.

6
  • How did you enter the interactive shell in both cases? Commented Aug 7, 2023 at 15:02
  • did you run import func in an interactive shell that had ALREADY imported func? if so, try again in a new shell Commented Aug 7, 2023 at 15:06
  • from comand line, I type python. My python version is 3.11.4 Commented Aug 7, 2023 at 15:07
  • @soundstripe, already tried. And even without relaunching the shell it seems to update when I modify the imported file Commented Aug 7, 2023 at 15:09
  • Ok I fixed the issue. I post will post an answer and close this question Commented Aug 7, 2023 at 15:11

1 Answer 1

0

I fixed this issue.

I tried making this script file (called myscript.sh) :

#!/usr/bin/python

import func

func.GetInstalledApps()

Then, if from command line (bash shell) I run :

./myscript.sh

It works. The remaining issue to figure out is why the code does not work from python interactive shell ?

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't answer the question, it just avoids the problem.
A script file doesn't really need to have a .sh extension... Naming your file that way is semantically wrong since your file is actually a Python file. You can name it myscript.py and it will work completely fine.
@Barmar A workaround is sometimes enough... But I would gladly know why it is not working in interactive shell.

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.