-1

I'm working on a function that generates a random file and then prints it; currently I have the following code :

    import os
    import random

    def randomfile(path):
        files = os.listdir(path)
        index = random.randrange(0, len(files))
        return files[index]

    pick = randomfile("~/me/Desktop/files")

    os.system("cat",pick) # Here i want to execute cat with the random file generated

Basically, I just want to print the generated file, how can I pass it to os.system ?

taylorSeries
  • 505
  • 2
  • 6
  • 18
P0MS
  • 43
  • 6
  • 1
    `os.system()` just takes a single string. You need to use concatenation or string formatting to combine the command name with the argument, e.g. `"cat " + pick` – Barmar May 25 '22 at 23:35
  • 4
    But you're better off using the `subprocess` module instead of `os.system()`. – Barmar May 25 '22 at 23:35
  • 1
    Why would you use `os.system()` to print a file? Just use `print(open(...).read())` – Barmar May 25 '22 at 23:37
  • 3
    What does your title have to do with the question? You're not passing multiple commands, you're asking how to pass a variable argument to the command. – Barmar May 25 '22 at 23:38
  • 2
    Note that `~` is not automatically translated to the home directory. Use `os.path.expanduser()` to convert to a real pathname. – Barmar May 25 '22 at 23:39
  • Side-note: The entire body of `randomfile` could simplify to `return random.choice(os.listdir(path))` – ShadowRanger May 25 '22 at 23:54
  • @Barmar: Just for fun/performance/not-blowing-memory-on-large-files, `sys.stdout.writelines(open(...))` (or with an import, `shutil.copyfileobj(open(...), sys.stdout)`, though the benefit is less there than normal, since copying by line instead of block makes more sense for often-line-oriented `stdout`). – ShadowRanger May 26 '22 at 15:19

3 Answers3

0

@Barmar Thanks mate I've used subprocess subprocess.run(["cat", pick]) Also print (open(pick).read()) it works for me thanks again

P0MS
  • 43
  • 6
-1

You can add it all into the os.system, such as os.system('cat' + pick). The other option would be to use the subprocess module and run subprocess.check_output("cat", pick). subprocess.check_output does return a value, so you'll either need to print it to the screen or do some manipulation of the return value, depending on what you want to do with it.

  • 3
    You need a space between the `cat` and the filename. Also, there are serious security problems here; what if `pick` is `$(rm -rf ~).txt`? – Charles Duffy May 26 '22 at 00:10
-1

You can use a for-loop to execute all commands from an array:

array = ['cat', 'pick']
for command in array:
os.system(command)
n4zgu1
  • 11
  • 1
  • 2
    Except `pick` isn't a second command to run, it's a filename to read. The OP's title is very misleading -- the question body completely changes what they're actually trying to do. – Charles Duffy May 26 '22 at 00:09