Python script to get file path: insert the result inside quotes

Hi,

I have a python script which copy the full path of text files opened in gedit:

#!/usr/bin/env python3

import subprocess
import sys

name = subprocess.check_output(["xdotool", "getactivewindow", "getwindowname"]).decode("utf-8").strip()
if all(["(" in name, ")" in name]):
    path = name[name.find("(")+1:name.find(")")]
    if sys.argv[1] == "-file":
        fname = name[:name.find("(")]
    elif sys.argv[1] == "-path":
        fname = ""
    command = "echo "+'"'+path+"/"+fname+'"'+" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"
    subprocess.Popen(["/bin/bash", "-c", command])

Works as expected, but I’d like to have the result reported inside quotes:

“path/to/file”

I’ve tried various attempts using sed, but the code looks “ugly”, “strange” and doesn’t work, maybe because this part

command = "echo "+'"'+path+"/"+fname+'"'+" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"

already have various quotation, and adding quotes to the code cause a mess.

How to achieve in the best way?

I might use something like

printf '"path/to/file"'

Doesn’t works.

You could use the format command

command = f"echo '{path}/{fname}' | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"

It would most likely be easier for you to use pyperclip

The path is still reported without quotes.

How to implement it? I am not expert with python; I found such script on stackexchange.

On my system it output as exepcted

 $ python
Python 3.11.3 (main, Apr  5 2023, 15:52:25) [GCC 12.2.1 20230201] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> path = "/path/to"
>>> fname = "fname"
>>> command = f"echo '{path}/{fname}'"
>>> print(command)
echo '/path/to/fname'

So not a problem with python.

It is likely your post processing in bash which strips your quotes - but I am not a shark on bash.

This is how I edit it:

#!/usr/bin/env python3

import subprocess
import sys

name = subprocess.check_output(["xdotool", "getactivewindow", "getwindowname"]).decode("utf-8").strip()
if all(["(" in name, ")" in name]):
    path = name[name.find("(")+1:name.find(")")]
    if sys.argv[1] == "-file":
        fname = name[:name.find("(")]
    elif sys.argv[1] == "-path":
        fname = ""
    command = f"echo '{path}/{fname}' | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"
    subprocess.Popen(["/bin/bash", "-c", command])

So? Sorry, but I don’t know anything about python…

I have no clue of what you are doing - but I know a little about python.

What I can see is that you genrating a command to executed by bash.

subprocess.Popen(["/bin/bash", "-c", command])

You could try escaping a set of double quotes

command = f"echo \"{path}/{fname}\" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"

Still no quotes :frowning:

Well it is not a python issue - to illustrate how Python generates the correct string using python print() I had to escape the \ in the delimiter \n - other than that python creates the expected string.

 $ python
Python 3.11.3 (main, Apr  5 2023, 15:52:25) [GCC 12.2.1 20230201] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> path = "/path/to"
>>> fname = "fname"
>>> command = f"echo '{path}/{fname}' | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"
>>> print(command)
echo '/path/to/fname' | tr -d '
' | sed 's/.$//' | xclip -selection clipboard
>>> command = f"echo '{path}/{fname}' | tr -d '\\n' | sed 's/.$//' | xclip -selection clipboard"
>>> print(command)
echo '/path/to/fname' | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard
>>> command = f"echo \"{path}/{fname}\" | tr -d '\\n' | sed 's/.$//' | xclip -selection clipboard"
>>> print(command)
echo "/path/to/fname" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard
>>> 

A computer is stupid - if you don’t get the result you expect then you are asking the wrong question - in other words your are providing the wrong input.

This is how I edited it again:

#!/usr/bin/env python3

import subprocess
import sys

name = subprocess.check_output(["xdotool", "getactivewindow", "getwindowname"]).decode("utf-8").strip()
if all(["(" in name, ")" in name]):
    path = name[name.find("(")+1:name.find(")")]
    if sys.argv[1] == "-file":
        fname = name[:name.find("(")]
    elif sys.argv[1] == "-path":
        fname = ""
    command = f"echo \"{path}/{fname}\" | tr -d '\\n' | sed 's/.$//' | xclip -selection clipboard"
    subprocess.Popen(["/bin/bash", "-c", command])

But I don’t still get quotes.

I suggest you go over your input - see what happens.

You can use print(variable) to see in real time what happens.

Try more backslashes.

command = f"echo \\"{path}/{fname}\\" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard"

No dice.

 $ python
Python 3.11.3 (main, Apr  5 2023, 15:52:25) [GCC 12.2.1 20230201] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import sys
>>> path="/path/to"
>>> names={"x","y","z"]
  File "<stdin>", line 1
    names={"x","y","z"]
                      ^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '{'
>>> names=["x","y","z"]
>>> for fname in names:
...     command=f"echo \"{path}/{fname}\" | tr -d '\\n' | sed 's/.$//' | xclip -selection clipboard"
...     print(command)
... 
echo "/path/to/x" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard
echo "/path/to/y" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard
echo "/path/to/z" | tr -d '\n' | sed 's/.$//' | xclip -selection clipboard

Check your input …

And please - this is not a Manjaro issue - so stop wasting time - have a nice day.

Well it works for me.

>>> command = f'echo \"{path}/{fname} \"'
>>> subprocess.run(command, shell=True)
/path/to/fname 
CompletedProcess(args='echo "/path/to/fname "', returncode=0)


>>> command = f'echo \\"{path}/{fname} \\"'
>>> subprocess.run(command, shell=True)
"/path/to/fname "
CompletedProcess(args='echo \\"/path/to/fname \\"', returncode=0)

command = f'echo \\"{path}/{fname} \\"'
>>> subprocess.Popen(["/bin/bash", "-c", command])
<Popen: returncode: None args: ['/bin/bash', '-c', 'echo \\"/path/to/fname \...>
>>> "/path/to/fname "

subprocess.Popen(["echo", f"\"{path}/{fname}\""])
<Popen: returncode: None args: ['echo', '"/path/to/fname"']>
>>> "/path/to/fname"

Not sure why the last 2 end up being printed as commands though but I rarely use the python command line or popen. @linux-aarhus Any ideas?

I originally opened this discussion in the Member Hub, but has been moved, by a moderator, in this section. If you think that is inappropriate, feel free to delete this discussion.

This would be a better question for https://stackoverflow.com/

I solved with a bash script:

#!/bin/bash

path=$(xdotool getactivewindow getwindowname | grep -oP '\(\K[^)]+')
path2="${path/#\~/$HOME}"
filename=$(xdotool getactivewindow getwindowname | cut -d"(" -f1 | rev | cut -c2- | rev)


echo "\"$path2/$filename"\" | tr -d '\n' | xclip -selection clipboard

And so, I got, eg: "/home/dave/Documents/text file"

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.