Home > Back-end >  if statement with input option? (Try to implement linux command lines)
if statement with input option? (Try to implement linux command lines)

Time:10-09

I'm trying to implement FTP client(only socket library) in Python, and try to make it work some command lines.

if statement

as screenshot above, mine of course working after I put cd command then user input is showing.

But I would like to make it " cd 'directory' ", which 'directory' is the user input.

Thank you for reading and helping in advance...

CodePudding user response:

I suggest splitting with packed values (to avoid a ValueError, but that's a styling choice):

user_cmd = "cd some/directory/perhaps with spaces/"
cmd, *args = user_cmd.split(" ", 1) # splits by spaces, stop after first split
args = args[0] if args else None

if cmd == "cd":
    if not args:
        raise ValueError("Missing argument: target directory")
    control_socket.send(...)

This way you can provide for a generic mechanism for commands that require arguments as well as commands that don't.

By the example you provided, you might need to further handle the directory argument (e.g. stripping the quotes). For that I suggest using either shlex or glob libraries (if you don't mind their strong affinity to UNIX-style paths), but this might be out of scope for your specific question.

CodePudding user response:

In this case, inside if condition you can execute cd command as follows:

import os

if cmd == "cd":
  path = input()
  cmd = 'cd '  path
  os.system(cmd)
  .
  .
  .
  • Related