I would like to know if there is a way to call module functions from the command line. My problem is that I have a file package called find_mutations. This requires that the input files are sorted in a specific way, so i made a function to do so. I would like the user to be able to have the option to run the code normally:
$ python -m find_mutations -h
or run the specific sort_files function:
$ python -m find_mutations.sort_files -h
Is something like this possible? If so, does the sort_files function need to be in its own strip? Do I need to add something to my __init__.py script? The package install properly and runs fine, I would just like to add this.
You could add flags to run the function. The following example is not a good way to work with command arguments, but demonstrates the idea.
import sys
if __name__ == "__main__":
if '-s' in sys.argv:
sort_files()
Add a flag to run the specific function, in this case -s to sort the files.
Related
So example I have got an effects.py file and to run on the command prompt, I am doing
gimp-console-2.10.exe -idf --batch-interpreter python-fu-eval -b "import effects; effects.data()" and this works.
However I don't really want to run it in this way. Is there a way I could run it like python effects.py on the command prompt instead?
#!/usr/bin/env python
from gimpfu import *
def data():
pass
If you want to avoid the import, you can install your python code as a regular plugin, and then you should be able to skip the import and call your plugin directly:
gimp-console-2.10.exe -idf --batch-interpreter python-fu-eval -b "pdb.python_fu_your_registration_atom(...)"
(not tested)
I want to create terminal commands in my python script.
for example,
$ cd my_project_folder
$ --help (I use a command in this python folder)
outputs
$ this is the help command. You've activated it using --help. This is only possible because you cd'd to the folder and inputted this command.
I am looking for user defined commands ( ones that I've already defined in my python function.)
I am not looking for commands like 'ls' and 'pwd'.
You can use os.system, as below:
import os
os.system('your command')
Use os module if you wanna execute command that is specific to bash or shell that you use
import os
os.system("string command")
As Leemosh sugested you can use click module to make your own commands that are related to scripts
And you can also use sys module to read args that you put affter your script
example
$ python3 name_of_script.py arg_n
import sys
if sys.argv[1] == "commnd":
do something
What you are looking for is creating a setup.py file and defining some entry points. I'd recommend watching https://www.youtube.com/watch?v=GIF3LaRqgXo&ab_channel=CodingTech or https://www.youtube.com/watch?v=4fzAMdLKC5ks&ab_channel=NextDayVideo to better understand how to deal with setup.py.
from setuptools import setup
setup(
name="Name_of_your_app",
version="0.0.1",
desciption="some description",
py_modules=["app"], # I think you don't need that
package_dir={"": "src"}, # and probably you don't need this as well
entry_points={"console_scripts": {"THIS_IS_THE_DEFINED_COMMAND=app:main"}},
)
app is name of the py file, main is function you wanna call.
app.py
def main():
print("hello")
I can run one program by typing: python enable_robot.py -e in the command line, but I want to run it from within another program.
In the other program, I imported subprocess and had subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e']), but I get an error message saying something about a callback.
If I comment out this line, the rest of my program works perfectly fine.
Any suggestions on how I could change this line to get my code to work or if I shouldn't be using subprocess at all?
If enable_robot.py requires user input, probably it wasn't meant to run from another python script. you might want to import it as a module: import enable_robot and run the functions you want to use from there.
If you want to stick to the subprocess, you can pass input with communicate:
p = subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])
p.communicate(input=b'whatever string\nnext line')
communicate documentation, example.
Your program enable_robot.py should meet the following requirements:
The first line is a path indicating what program is used to interpret
the script. In this case, it is the python path.
Your script should be executable
A very simple example. We have two python scripts: called.py and caller.py
Usage: caller.py will execute called.py using subprocess.Popen()
File /tmp/called.py
#!/usr/bin/python
print("OK")
File /tmp/caller.py
#!/usr/bin/python
import subprocess
proc = subprocess.Popen(['/tmp/called.py'])
Make both executable:
chmod +x /tmp/caller.py
chmod +x /tmp/called.py
caller.py output:
$ /tmp/caller.py
$ OK
I have a fabric script called fwp.py that I run without calling it throug fab by using:
if __name__ == '__main__':
# imports for standalone mode only
import sys
import fabric.main
fabric.main.main(fabfile_locations=[__file__])
The thing is then have to call the script by calling fwp.py. I'd like to rename it as fwp to be able to call it as fwp. But doing that would result in
Fatal error: Couldn't find any fabfiles!
Is there a way to make Python/Fabric import this file, despite the lack of a ".py" extension?
To reiterate and clarify:
I'm not using the "fab" utility (e.g. as fab task task:parameter); just calling my script as fwp.py task task:parameter, and would like to be able to call it as fwp task task:parameter.
Update
It's not a duplicate of this question. The question is not "How to run a stand-alone fabric script?", but "How to do so, while having a script without a .py" extension.
EDIT: Original answer corrected
The fabric.main.main() function automatically adds .py to the end of supplied fabfile locations (see https://github.com/fabric/fabric/blob/master/fabric/main.py#L93). Unfortunately that function also uses Python's import machinery to load the file so it has to look like a module or package. Without reimplementing much of the fabric.main module I don't think it will be possible. You could try monkey-patching both fabric.main.find_fabfiles and fabric.main.load_fabfiles to make it work.
Origininal answer (wrong)
I can get this to work unaltered on a freshly installed fabric package. The following will execute with a filename fwp and executable permission on version 1.10.1, Python2.7. I would just try upgrading fabric.
#!/usr/bin/env python
from fabric.api import *
import fabric.main
def do():
local('echo "Hello World"')
if __name__ == '__main__':
fabric.main.main(fabfile_locations=[__file__])
Output:
$ ./fwp do
Hello World
Done
I am trying to execute a program from a directory
import os
os.chdir("/home/user/a/b")
with cd("/home/user/a/b"):
run ("./program")
i get cd is not defined...
any help appreciated cheers
I'm not sure what instructions you're following to get what you showed. There is no built-in function called cd or run in Python.
You can call a program in a specific directory using the subprocess module:
import subprocess
subprocess.call("./program", cwd="/home/user/a/b")
The cwd argument causes the call function to automatically switch to that directory before starting the program named in the first argument.
It looks like you are trying to use functionalities of fabric. Make sure fabric is installed, and cd and run are imported from fabric. Something like,
from fabric.context_managers import cd
from fabric.operations import run
import os
os.chdir("/home/user/a/b")
with cd("/home/user/a/b"):
run ("./program")
Save your file as fabfile.py,and from the same directory run it as:
fab -H localhost
For more information on the fabric, checkout: fabric