0

How can we use python run its script in line ? e.g.

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("test-script.py")
for name, mod in finder.modules.items():
   print(name)

Have tried such its one line:

$ python -c 'from modulefinder import ModuleFinder; finder = ModuleFinder(); finder.run_script("/usr/bin/xbacklight"); for name, mod in finder.modules.items(): print(name)'
  File "<string>", line 1
    from modulefinder import ModuleFinder; finder = ModuleFinder(); finder.run_script("/usr/bin/xbacklight"); for name, mod in finder.modules.items(): print(name)
                                                                                                              ^^^
SyntaxError: invalid syntax

How to do it finely working? Thanks before

itil memek cantik
  • 1,167
  • 2
  • 11
  • Out of curiosity, why would you like to do this? The [PEP 8 guidelines](https://peps.python.org/pep-0008/#maximum-line-length) suggest a maximum line length of 79 characters as a standard (See [this question](https://stackoverflow.com/questions/88942/why-does-pep-8-specify-a-maximum-line-length-of-79-characters) and associated answers for more in-depth discussion and arguments on why) – G. Anderson Jun 23 '22 at 23:36

2 Answers2

1

You can wrap your for-each inside a list comprehension in order to make it work using a single-line instruction.

The command becomes

python -c 'from modulefinder import ModuleFinder; finder = ModuleFinder(); finder.run_script("/usr/bin/xbacklight"); [print(name) for name, mod in finder.modules.items()]'
canta2899
  • 394
  • 1
  • 7
1

You can use a here-document. Once you've entered <<something, the shell will pipe all input until it sees "something" again to stdin. Commonly, "EOF" is used.

$ python <<EOF
> from modulefinder import ModuleFinder
> finder = ModuleFinder()
> finder.run_sctript("test-script.py")
> for name, mod in finder.modules.items():
>     print(name)
> EOF
tdelaney
  • 73,364
  • 6
  • 83
  • 116