The Stack Overflow podcast is back! Listen to an interview with our new CEO.

Hot answers tagged

163

sudo python -m SimpleHTTPServer 80 for python 3.x version, you may need : sudo python -m http.server 80 Ports below 1024 require root privileges. As George added in a comment, running this command as root is not a good idea - it opens up all kinds of security vulnerabilities. However, it answers the question.


154

You can install Python-3.6 on Debian 8 as follows: wget https://www.python.org/ftp/python/3.6.9/Python-3.6.9.tgz tar xvf Python-3.6.9.tgz cd Python-3.6.9 ./configure --enable-optimizations --enable-shared make -j8 sudo make altinstall python3.6 It is recommended to use make altinstall according to the official website. If you want pip to be included, you ...


106

You can use os.system(), like this: import os os.system('ls') Or in your case: os.system('echo 1 > /proc/sys/net/ipv4/ip_forward') os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080') Better yet, you can use subprocess's call, it is safer, more powerful and likely faster: from subprocess import call call('...


93

From the comment: sudo update-alternatives --config python Will show you an error: update-alternatives: error: no alternatives for python3 You need to update your update-alternatives , then you will be able to set your default python version. sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.4 1 sudo update-alternatives --...


80

Ubuntu 16.10+ and Python 3.7 dev sudo apt-get install zlib1g-dev note: i only put this here because it was the top search result for the error, but this resolved my issue. update: also the case for ubuntu 14.04LTS and base kernel at 4.1+


66

Debian does not have Python 3.6 in its repositories, but testing has it. $ sudo nano /etc/apt/sources.list # add deb http://ftp.de.debian.org/debian testing main $ echo 'APT::Default-Release "stable";' | sudo tee -a /etc/apt/apt.conf.d/00local $ sudo apt-get update $ sudo apt-get -t testing install python3.6 $ python3.6 -V You asked for: the proper and ...


64

This is happening because normally when process STDOUT is redirected to something other than a terminal, then the output is buffered into some OS-specific-sized buffer (perhaps 4k or 8k in many cases). Conversely, when outputting to a terminal, STDOUT will be line-buffered or not buffered at all, so you'll see output after each \n or for each character. ...


55

How many lines are in each file. Use wc, originally for word count, I believe, but it can do lines, words, characters, bytes, and the longest line length. The -l option tells it to count lines. wc -l <filename> This will output the number of lines in : $ wc -l /dir/file.txt 32724 /dir/file.txt You can also pipe data to wc as well: $ cat /dir/file....


49

jq has a filter, @csv, for converting an array to a CSV string. This filter takes into account most of the complexities associated with the CSV format, beginning with commas embedded in fields. (jq 1.5 has a similar filter, @tsv, for generating tab-separated-value files.) Of course, if the headers and values are all guaranteed to be free of commas and ...


44

This should do the job: import time, sys for i in range(10): print('bla') sys.stdout.flush() time.sleep(5) As Python will buffer the stdout by default, here i have used sys.stdout.flush() to flush the buffer. Another solution would be to use the -u(unbuffered) switch of python. So, the following will do too: python -u script.py >> log


42

The table in this Stack Overflow answer (which got it from the Bash Hackers Wiki) explains how the different Bash variables are expanded: You're doing python -i -c "from $@", which turns into python -i -c "from sys" "import" "stdout", and -c only takes a single argument, so it's running the command from sys. You want to use $*, which will expand into python ...


42

To run a set of Python commands from a bash script, you must give the Python interpreter the commands to run, either from a file (Python script) that you create in the script, as in #!/bin/bash -e # Create script as "script.py" cat >script.py <<'END_SCRIPT' print("TESTPRINT") END_SCRIPT # Run script.py python script.py rm script.py (this ...


37

Python Add to file named csv2tab.sh, and make it executable #!/usr/bin/env python import csv, sys csv.writer(sys.stdout, dialect='excel-tab').writerows(csv.reader(sys.stdin)) Test runs $ echo 'A,,C,"D,E,F","G",I,"K,L,M",Z' | ./csv2tab.sh A C D,E,F G I K,L,M Z $ ./csv2tab.sh < data.csv > data.tsv && ...


35

You have two main choices: Run the command with nohup. This will disassociate it from your session and let it continue running after you disconnect: nohup pythonScript.py Note that the stdout of the command will be appended to a file called nohup.out unless you redirect it (nohup pythonScript.py > outfile). Use a screen multiplexer like tmux. This will ...


32

If you don't need the python packages for all users then you can install them in your home like this: pip install --user packagename Installing in your home will not conflict with the package manager. By default pip install --user will install in your "user site" directory. Usually that is something like: /home/lesmana/.local/lib/python3.6/site-packages. ...


32

I prefer to make each record an row in my CSV. jq '.data | map([.displayName, .rank, .value] | join(", ")) | join("\n")'


32

The official recommendation is "you don't actually need newer software" Don't suffer from Shiny New Stuff Syndrome - DontBreakDebian | Debian Wiki Most of the advice on that page is geared towards what to do if you want the software to be available system-wide, but I don't think that's necessary in this case. If you fetch the python sources, build the 3.6 ...


31

Apparently, recent kernel versions introduced a blank line in /proc/(pid)/status that iotop does not expect: CapBnd: 0000001fffffffff CapAmb: 0000000000000000 Seccomp: 0 SpeculationStoreBypass: vulnerable As a zeroth approximation of a fix, edit (as root) /usr/lib/python2.7/site-packages/iotop/data.py ca l.195: def parse_proc_pid_status(pid): ...


30

Given just this file, you can do something like: <testfile jq -r '.data | map(.displayName), map(.value) | join(", ")' The . operator selects a field from an object/hash. Thus, we start with .data, which returns the array with the data in it. We then map over the array twice, first selecting the displayName, then selecting the value, giving us two ...


29

The shebang line is very limited. Under many unix variants (including Linux), you can have only two words: a command and a single argument. There is also often a length limitation. The general solution is to write a small shell wrapper. Name the Python script foo.py, and put the shell script next to foo.py and call it foo. This approach doesn't require any ...


29

The first command simply writes to a file. You wouldn't execute that as a shell command because python can read and write to files without the help of a shell: with open('/proc/sys/net/ipv4/ip_forward', 'w') as f: f.write("1") The iptables command is something you may want to execute externally. The best way to do this is to use the subprocess module. ...


28

In Ubuntu 14.04 try: sudo ln -s /usr/include/freetype2 /usr/local/include/freetype


28

From AskUbuntu, answer by Gilles: If you see the error “: No such file or directory” (with nothing before the colon), it means that your shebang line has a carriage return at the end, presumably because it was edited under Windows (which uses CR,LF as a line separator). The CR character causes the cursor to move back to the beginning of the line after the ...


27

Ok after a lot of searching I decided to build Python from source, so I downloaded the compressed source tarball from the Python download page, now we need to install the build-essential package to be able to compile the source files: apt-get install build-essential also we need to install these development packages which are required for some Python ...


27

This worked for me: import sys firstarg=sys.argv[1] secondarg=sys.argv[2] thirdarg=sys.argv[3]


25

If you would use: $ cat members.json | \ python -c 'import json,sys;obj=json.load(sys.stdin);print obj;' you can inspect the structure of the nested dictonary obj and see that your original line should read: $ cat members.json | \ python -c 'import json,sys;obj=json.load(sys.stdin);print obj["hits"]["hits"][0]["_source"]["'$1'"]'; to the to ...


25

Python imports a large number of files at startup: % python -c 'import sys; print len(sys.modules)' 39 Each of these requires an even greater number of attempts at opening a Python file, because there are many ways to define a module: % python -vv -c 'pass' # installing zipimport hook import zipimport # builtin # installed zipimport hook # trying site.so ...


25

The solution is : # yum install zlib-devel


23

You need the python development headers, and possibly other development packages. Easiest way to get them is: sudo apt-get build-dep python-imaging


23

On Ubuntu (until 14.04, 16.04 and later use systemd) can use upstart to do so, better than a cron job. You put a config setup in /etc/init and make sure you specify respawn It could be a minimal file /etc/init/testing.conf (edit as root): chdir /your/base/directory exec python testing.py respawn And you can test with /your/base/directory/testing.py: from ...


Only top voted, non community-wiki answers of a minimum length are eligible