I have some code and I would like to use scriptine to create several commands for a single script. Here's my code so far:
from scriptine import run, path, log
import sys
import mymodule1 as m1
import mymodule2 as m2
def load_command():
'''
Load something
'''
m1.main()
def exec_command():
'''
Exec something
'''
m2.main()
if __name__ == '__main__':
run()
But when i run it, nothing happens. I cannot figure out what I'm missing. I've tested both main() functions inside each module and they're OK.
Thanks in advance
Your code works for me.
If you're running on Linux, I would add the first line to the .py file:
#!/usr/bin/env python
And then make it executable:
> chmod +x myfile.py
Then you can run your command like this:
> ./myfile.py load
> ./myfile.py exec
Otherwise, you can run your command like this:
> python myfile.py load
> python myfile.py exec
Related
In my main Python script, I want to call another python script to run, as follows:
python2 ~/script_location/my_side_script.py \ --input-dir folder1/in_folder \ --output-dir folder1/out_folder/ \ --image-ext jpg \
From inside my Python script, how exactly can I do this?
I will be using both Windows and Ubuntu, but primarily the latter. Ideally would like to be able to do on both.
You could import the script in your main file.
Suppose you have two files: myscript.py and main.py
# myscript.py
print('this is my script!')
# main.py
print('this is my main file')
import myscript
print('end')
The output if you run main.py would be:
this is my main file
this is my script
end
EDIT: If you literally just want to call python2 my_side_script.py --options asdf, you could use the subprocess python module:
import subprocess
stdout = subprocess.check_output(['python2', 'my_side_script.py', '--options', 'asdf'])
print(stdout) # will print any output from your sidescript
I have several command execution in python on Windows using subprocess.call(), but for each one I need to execute batch file with environmet setup before calling proper command, it looks like this
subprocess.call(precommand + command)
Is there way to "create" shell in python that will have batch file executed only once and in that shell command will be executed several times?
Write commands to a bat-file (tempfile.NamedTemporaryFile())
Run the bat-file (subprocess.check_call(bat_file.name))
(not tested):
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import tempfile
with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file:
print(precommand, file=bat_file)
print(command, file=bat_file)
rc = subprocess.call(bat_file.name)
os.remove(bat_file.name)
if rc != 0:
raise subprocess.CalledProcessError(rc, bat_file.name)
Do you need to get output from every command separately? If no - you can convey these commands using &&, || or ;
cd dir && cp test1 test2 && cd -
How do I run a python script from within the IDLE interactive shell?
The following throws an error:
>>> python helloworld.py
SyntaxError: invalid syntax
Python3:
exec(open('helloworld.py').read())
If your file not in the same dir:
exec(open('./app/filename.py').read())
See https://stackoverflow.com/a/437857/739577 for passing global/local variables.
In deprecated Python versions
Python2
Built-in function: execfile
execfile('helloworld.py')
It normally cannot be called with arguments. But here's a workaround:
import sys
sys.argv = ['helloworld.py', 'arg'] # argv[0] should still be the script name
execfile('helloworld.py')
Deprecated since 2.6: popen
import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout
With arguments:
os.popen('python helloworld.py arg').read()
Advance usage: subprocess
import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
With arguments:
subprocess.call(['python', 'helloworld.py', 'arg'])
Read the docs for details :-)
Tested with this basic helloworld.py:
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
You can use this in python3:
exec(open(filename).read())
The IDLE shell window is not the same as a terminal shell (e.g. running sh or bash). Rather, it is just like being in the Python interactive interpreter (python -i). The easiest way to run a script in IDLE is to use the Open command from the File menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run -> Run Module command (shortcut F5).
EASIEST WAY
python -i helloworld.py #Python 2
python3 -i helloworld.py #Python 3
Try this
import os
import subprocess
DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')
subprocess.call(['python', DIR])
execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)
For example, execFile('C:/helloworld.py')
In a python console, one can try the following 2 ways.
under the same work directory,
1.
>> import helloworld
# if you have a variable x, you can print it in the IDLE.
>> helloworld.x
# if you have a function func, you can also call it like this.
>> helloworld.func()
2.
>> runfile("./helloworld.py")
For example:
import subprocess
subprocess.call("C:\helloworld.py")
subprocess.call(["python", "-h"])
In Python 3, there is no execFile. One can use exec built-in function, for instance:
import helloworld
exec('helloworld')
In IDLE, the following works :-
import helloworld
I don't know much about why it works, but it does..
To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:
>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)
I'm using Python 3.4. See the compile and exec docs for detailed info.
I tested this and it kinda works out :
exec(open('filename').read()) # Don't forget to put the filename between ' '
you can do it by two ways
import file_name
exec(open('file_name').read())
but make sure that file should be stored where your program is running
On Windows environment, you can execute py file on Python3 shell command line with the following syntax:
exec(open('absolute path to file_name').read())
Below explains how to execute a simple helloworld.py file from python shell command line
File Location: C:/Users/testuser/testfolder/helloworld.py
File Content: print("hello world")
We can execute this file on Python3.7 Shell as below:
>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'
>>> exec(open("helloworld.py").read())
hello world
>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world
>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world
There is one more alternative (for windows) -
import os
os.system('py "<path of program with extension>"')
I have a demo file: test.py.
In the Windows Console I can run the file with: C:\>test.py
How can I execute the file in the Python Shell instead?
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
It depends on what is in test.py. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
For newer version of python:
exec(open(filename).read())
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
From the same folder, you can do:
import test
So, I created a simple python module, test.py
import commands
def main():
cmd = 'ls -l'
(status, output) = commands.getstatusoutput(cmd)
print status, output
if __name__ == '__main__':
main()
When I ran it using "Python test.py", I got the result that I expected. But when I ran it as an executable (yes, it has the 'x' permission), the program didn't respond at all and I had to Ctrl+C to quit it. Why is that? Shouldn't both ways give the same result?
Add a hash-bang line to the top:
#!/usr/bin/env python
import commands
...
This tells your system what interpreter to use to execute the script. Without it it doesn't know if it's a shell script, Perl script, Python script, what.
You need the hashbang to be the first line of your script, referencing the path of the Python interpreter. Otherwise, all the OS knows is that you're trying to execute a script, and it has no idea how to go about doing that.