Python URL call using xdg Linux command - python

I have been trying to get this simple url call Linux command to run as a python script. However, I keep getting an error for too many arguments in the system() module. Is there is easy fix still using this technique?
import sys
import os
g = str(input('enter search '))
os.system('xdg-open https://',g)

format the command as a single string instead of 2 parameters
import sys
import os
search = str(input('enter search'))
os.system(f'xdg-open https://{search}')

Related

How to run a function by passing the arguments and retrieve the results

I have a script myScript.py with a function myFunc(a, b). How can I use subprocess module to run this function on a given conda environment with a given arguments? The solution which I would like to obtain is:
import subprocess
result = subprocess.run(["path\to\python", nameOfFunction, arguments a and b])
where result is a result of a function myFunc(a,b).
you can simply do this
import subprocess
result = subprocess.run(["path\to\python", "-c","import pyfile;myFunc(5, 10)"])
but if your file is in another directory
you can use two ways
this going to append directory path to python sys paths
import sys;sys.path.append("path\to\pyfile/directory")
then import it
or
import os;os.chdir("path\to\pyfile/directory")
learn more about os.chdir and sys.path
if you don't know why did i put the -c in subprocess.run, here something that will be helpful python cmdline

How to call other python script in another python script?

I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?
Example:
case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.
final.py is my another script in which I am trying to call above script and store return value into a variable.
I am trying to do in python :
import case as f_case
qry = ''
qry += f_case.generate_case('R162')
print(qry)
Error:
ModuleNotFoundError: No module named 'case'
Both the scripts are available in the same location.
Try this
import os
import sys
scriptpath=''
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import case as f_case
I rename the script as new_cons.py. Now it working for me. May be in script name I have added integer so it is not importing the script.

How to call a function using the Visual Studio Code terminal

I have created a python script with a single function in it. Is there a way to call the function from the python terminal to test some arguments?
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end='', flush=True)
time.sleep(random.randint(1,2)/20)
If I want to test an argument for the function, I would have to add string_teletyper(argument) inside the script itself and run it, is there a faster way?
you can do,
>>> from yourfilename import *
>>> string_teletyper(arg)
import all function or specific function from the file and you don't need to put .py at the end of yourfilename when you used it as a module.
Running parts of a Python module many times during development is a common development task. The way most Python developers do this is to use the following code:
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end='', flush=True)
time.sleep(random.randint(1,2)/20)
if __name__ == "__main__":
test_st = 'My string to test as an argument'
string_teletyper(test_st)
This means that anything in the if block will only get ran if the module is called via $python my_file.py and not called in a module.

Python: Click Package - Having trouble with non ASCII chars & cmd.exe

I am writing a command line tool using the Click Python Package:
http://click.pocoo.org/5/
Which is quite usefull but I can't get one issue fixed with that, which is when I enter non ASCII chars as parameter for my Command Line Tool, it will always give me that encoding error:
And yeah I know about encode() and decode() in python, but as you can see in my code I am not touching this string anywhere.
Is it the fault of my console? Am I missing any settings here? I am using Windows 7 cmd.exe and know that Windows likes his own encoding for filenames etc. Do I have to use another console? Tried python one with same result.
The click Documentation states all strings are treated as Unicode...
I would appreciate your help really much.
Installing click is as easy as pip install click
Kind regards,
Marcurion
My Code:
import click
from click_shell import shell
import os
#shell(prompt='Tool > ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__)))
def stRec():
pass
#stRec.command()
#click.argument('name', required=True, type=click.STRING)
def set(name):
print "nothing"
if __name__ == '__main__':
stRec()
I found it out, had to add this on top of the other import statements (all lines are important):
#!/usr/bin/python -S
import sys
reload(sys)
sys.setdefaultencoding("cp1252")
import site
cp1252 is the encoding reported to me by
import locale
print locale.getpreferredencoding()
However the encoding of my "name" parameter was not cp1252 when I got it, had to find out with chardet lib (pip install chardet)that it was actually ISO-8859-9. So since I wanted to create a folder with this argument I encoded it back to cp1252:
#!/usr/bin/python -S
import sys
reload(sys)
sys.setdefaultencoding("cp1252")
import site
import click
from click_shell import shell
import os
import locale
import chardet
#shell(prompt='Tool > ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__)))
def stRec():
pass
#stRec.command()
#click.argument('name', required=True, type=click.STRING)
def set(name):
# Create folder in the folder running this script
folderPath = os.path.join(os.path.split(os.path.abspath(__file__))[0], name)
folderPath = folderPath.decode(str(chardet.detect(bytes(folderPath))['encoding'])).encode(locale.getpreferredencoding())
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if __name__ == '__main__':
stRec()

Accessing a function from a module

I cant figure out how to add my simple function to my main program file. why not ?
when i do this:
import print_text
echothis("this is text")
exit()
cant understand why people think this is such a bad question.
this doesnt work either:
print_text.echothis("this is text")
same thing happens if i type any of the answers below.
including:
from print_text import echothis
I just get this error:
from: can't read /var/mail/print_text
./blah3.py: line 3: syntax error near unexpected token `"this is text"'
./blah3.py: line 3: `print_text.echothis("this is text")'
or a variant without the /var/mail line...
*this file is named print_text.py*
#!/usr/bin/env python
import time
import random
import string
import threading
import sys
def echothis(txt):
woo=txt
stdout.write(woo)
EDIT: You're actually not having a python issue but a bash one. You're running your python script as if it were bash (hence the 'from: can't read from'), did you put #!/usr/bin/env python at the beginning of the file you're running (not print_text.py, the other one)? You could alternatively call it that way: python myfile.py and it should work.
When you import a module, it is namespaced, so if you want to use anything that is from that module, you need to call it using the proper namespace. Here, you would call you echothis function using print_text.echothis.
Alternatively, if you want to include echothis in your main namespace, you can use the from print_text import echothis syntax.
Try this:
import print_text
print_text.echothis("this is a text")

Categories

Resources