2

I'm trying to execute a shell command from python. Here's the command :

(flock -n 200 || (echo no; exit 1) && (echo yes; cat /home/user/Desktop/instructions.json; >/home/user/Desktop/instructions.json)) 200>>/home/user/Desktop/instructions.json

I tried os.system() or subprocess.call(); However I always have the same error which is :

/bin/sh: 1: Syntax error: word unexpected

I think the problem is due to parentheses but I'm not sure.

I'm trying to read the file thanks to cat then delete its content IF it's not locked else just echo no and exit.

This command works in shell.

Stoogy
  • 1,307
  • 3
  • 16
  • 34
MelKoutch
  • 180
  • 1
  • 12
  • When you say that "[t]his command works in shell", do you mean you run it in Bash? Bash have some extensions compared to a more bare-bones shell like `sh` might be. If you open a new terminal and start `sh` (`/bin/sh`) and attempt to run your command, does it work then? – Some programmer dude Nov 27 '18 at 09:27
  • No it doesn't, sorry for miswriting I meant that the command works when I open a new terminal and paste it directly. – MelKoutch Nov 27 '18 at 09:32
  • Then you're most likely running it in Bash. From the terminal run `/bin/sh` and paste the full command again. Does it work? – Some programmer dude Nov 27 '18 at 09:40
  • I tried and it doesn't work, I've the following error : bash: syntax error near the unexpected "flock" symbol – MelKoutch Nov 27 '18 at 09:42
  • You haven't even shown the code that you are trying in Python. Please post that. – Daniel Roseman Nov 27 '18 at 10:07
  • Yes indeed, sorry here's what I tested : subprocess.call("(flock -n 200 || (echo no; exit 1) && (echo yes; cat /home/user/Desktop/instructions.json; >/home/user/Desktop/instructions.json)) 200>>/home/user/Desktop/instructions.json", shell = True) --- I managed to fix my problem though ! – MelKoutch Nov 27 '18 at 10:47

2 Answers2

1

To execute a command from python ad it would in the shell, use shell=true as an argument:

subprocess.call("your command", shell=true)

see this post

Jean Bouvattier
  • 303
  • 3
  • 19
  • 1
    I tried but it doesn't work. With shell=true I get /bin/sh: 1: Syntax error: word unexpected. When I don't put shell=true I get "FileNotFoundError: [Errno 2] No such file or directory: '(flock -n 200 || ..." – MelKoutch Nov 27 '18 at 09:33
1

It seems you are trying to lock a file in Python.

In your case you have two opportunities :

  • You can use the python function fcntl.flock() to directly lock a file
  • You can also use a simple script sh in which you write #!/bin/sh, at the beginning
WR.
  • 96
  • 5